问题
I have a type in Java called Item which is defined as follows:
private Integer itemNo;
private String itemName;
private String itemDescription;
...
And I would like to be able to sort an arraylist of this type in descending order according to itemName.
From what I read, this can be done via:
Collections.sort(items, Collections.reverseOrder());
Where items is:
ArrayList<Item> items = new ArrayList<Item>();
But I find that the call to Collections.sort gives me a:
Item cannot be cast to java.lang.Comparable
Run time exception.
Can anyone advise on what I need to do?
回答1:
Declare Item to be Comparable, and implement the comapreTo method to compare itemName
in reverse order (ie compare "that to this", rather than the normal "this to that").
Like this:
public class Item implements Comparable<Item> {
private Integer itemNo;
private String itemName;
private String itemDescription;
public int compareTo(Item o) {
return o.itemName.compareTo(itemName); // Note reverse of normal order
}
// rest of class
}
回答2:
You need your custom Item
to implement Comparable
, or otherwise you can do it using Comparator
回答3:
You should probably make Item implement Comparable, or create a Comparator to your Item, and use Collections.sort(List,Comparator)
code snap:
Comparator:
public static class MyComparator implements Comparator<Item> {
@Override
public int compare(Item o1, Item o2) {
//reverse order: o2 is compared to o1, instead of o1 to o2.
return o2.getItemName().compareTo(o1.getItemName());
}
}
usage:
Collections.sort(list,new MyComparator());
(*)note that the static
keyword in MyComparator
's declaration is because I implemented it as an inner class, if you implement this class as an outer class, you should remove this keyword
回答4:
You need to implement the Comparable interface and define the compareTo(T o) method.
See also:
- How to use Comparable Interface
回答5:
You need to make your Item class implement the java.lang.Comparable interface.
public class Item implements Comparable<Item> {
// your code here, including an implementation of the compare method
}
来源:https://stackoverflow.com/questions/7514451/sorting-an-arraylist-of-my-own-type-in-java