在Java中对我自己类型的arraylist进行排序

Mr *_*gan 2 java collections

我有一个名为Item的Java类型,定义如下:

private Integer itemNo;
private String itemName;
private String itemDescription;
...
Run Code Online (Sandbox Code Playgroud)

我希望能够根据itemName按降序对这种类型的arraylist进行排序.

从我读到的,这可以通过以下方式完成:

Collections.sort(items, Collections.reverseOrder());
Run Code Online (Sandbox Code Playgroud)

物品是:

ArrayList<Item> items = new ArrayList<Item>();
Run Code Online (Sandbox Code Playgroud)

但我发现对Collections.sort的调用给了我一个:

Item cannot be cast to java.lang.Comparable
Run Code Online (Sandbox Code Playgroud)

运行时异常.

有人可以建议我需要做什么吗?

Boh*_*ian 6

申报项目是可比,并实现comapreTo方法来比较itemName相反的顺序(即比较" 这个 ",而不是正常的" ").

像这样:

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
}
Run Code Online (Sandbox Code Playgroud)