在Java中排序我自己类型的数组列表 [英] Sorting an arraylist of my own type in Java

查看:85
本文介绍了在Java中排序我自己类型的数组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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());

其中项目是:

ArrayList<Item> items = new ArrayList<Item>();

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

But I find that the call to Collections.sort gives me a:

Item cannot be cast to java.lang.Comparable

运行时异常。

任何人都可以告诉我我需要做什么?

Can anyone advise on what I need to do?

推荐答案

声明项目可比较,并实施 comapreTo 方法比较 顺序中 itemName (即将 >此,而不是正常的 )。

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").

像这样:

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
}

这篇关于在Java中排序我自己类型的数组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆