【问题标题】:Sorting an arraylist of my own type in Java在 Java 中对我自己类型的数组列表进行排序
【发布时间】:2011-09-22 12:04:24
【问题描述】:

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

private Integer itemNo;
private String itemName;
private String itemDescription;
...

并且我希望能够根据 itemName 以降序对这种类型的数组列表进行排序。

根据我的阅读,这可以通过以下方式完成:

Collections.sort(items, Collections.reverseOrder());

项目在哪里:

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

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

Item cannot be cast to java.lang.Comparable

运行时异常。

谁能建议我需要做什么?

【问题讨论】:

    标签: java collections


    【解决方案1】:

    将Item声明为Comparable,并实现comapreTo方法以反向顺序比较itemName(即比较“thatthis ”,而不是普通的“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
    }
    

    【讨论】:

      【解决方案2】:

      你需要你的自定义 Item 来实现 Comparable ,否则你可以做到 using Comparator

      【讨论】:

        【解决方案3】:

        您可能应该让 Item 实现 Comparable为您的 Item 创建一个 Comparator,然后使用 Collections.sort(List,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()); 
            }
        }
        

        用法:

            Collections.sort(list,new MyComparator());
        

        (*)注意MyComparator的声明中的static关键字是因为我把它实现为一个内部类,如果你把这个类实现为一个外部类,你应该去掉这个关键字

        【讨论】:

          【解决方案4】:

          你需要实现Comparable接口并定义compareTo(T o)方法。

          另见:

          【讨论】:

            【解决方案5】:

            你需要让你的 Item 类实现 java.lang.Comparable 接口。

            public class Item implements Comparable<Item> {
            
               // your code here, including an implementation of the compare method
            }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2019-08-05
              • 2016-03-01
              • 2019-06-09
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2017-12-13
              • 1970-01-01
              相关资源
              最近更新 更多