开发者

Sorting an arraylist of my own type in Java

开发者 https://www.devze.com 2023-04-06 21:40 出处:网络
I have a type in Java called Item which is defined as follows: private Integer itemNo; private String itemName;

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());
开发者_如何学Go

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 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
}


You need your custom Item to implement Comparable , or otherwise you can do it using Comparator


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


You need to implement the Comparable interface and define the compareTo(T o) method.

See also:

  • How to use Comparable Interface


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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号