在 Java 中对我自己类型的数组列表进行排序
我在 Java 中有一个名为 Item 的类型,其定义如下:
private Integer itemNo;
private String itemName;
private String itemDescription;
...
我希望能够根据 itemName 对这种类型的数组列表进行降序排序。
根据我的阅读,这可以通过以下方式完成:
Collections.sort(items, Collections.reverseOrder());
Where items is:
ArrayList<Item> items = new ArrayList<Item>();
但我发现对 Collections.sort 的调用给了我一个:
Item cannot be cast to java.lang.Comparable
运行时异常。
谁能建议我需要做什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
将 Item 声明为 Comparable,并实现comapreTo 方法比较
itemName
按相反顺序(即将“that 与this”进行比较,而不是正常的“this” 到那个”)。像这样:
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:
您需要自定义
Item
来实现Comparable
,否则您可以使用比较器You need your custom
Item
to implementComparable
, or otherwise you can do it using Comparator您可能应该使 Item 实现 Comparable ,或创建一个比较器您的项目,并使用 Collections.sort(List,Comparator)
代码快照:
Comparator:
用法:
(*)注意
MyComparator
声明中的static
关键字是因为我将其实现为内部类,如果您将此类实现为外部类,你应该删除这个关键字You should probably make Item implement Comparable, or create a Comparator to your Item, and use Collections.sort(List,Comparator)
code snap:
Comparator:
usage:
(*)note that the
static
keyword inMyComparator
'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您需要实现
Comparable
接口并定义compareTo(T o)
方法。另请参阅:
You need to implement the
Comparable
interface and define thecompareTo(T o)
method.See also:
您需要使您的 Item 类实现 java.lang.Comparable 接口。
You need to make your Item class implement the java.lang.Comparable interface.