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?
Declare Item to be Comparable, and implement the comapreTo method to compare
itemNamein reverse order (ie compare “that to this“, rather than the normal “this to that“).Like this: