Reputation: 2243
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?
Upvotes: 2
Views: 1730
Reputation: 425198
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
}
Upvotes: 6
Reputation: 178491
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
Upvotes: 2
Reputation: 52468
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
}
Upvotes: 0
Reputation: 829
You need to implement the Comparable
interface and define the compareTo(T o)
method.
See also:
Upvotes: 0
Reputation: 240928
You need your custom Item
to implement Comparable
, or otherwise you can do it using Comparator
Upvotes: 2