使用哈希码对对象的ArrayList进行排序 [英] Sorting ArrayList of Objects using Hashcode

查看:94
本文介绍了使用哈希码对对象的ArrayList进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象的ArrayList(POJO),它们具有一个ID和另一个字段.我已经在POJO中为Id字段实现了equals()/hashcode()重写.当我使用Object类的equals()方法比较两个对象时,它可以很好地工作.但是,当我将这些对象添加到arraylist并实现

I have an ArrayList of Objects(POJOs) that have an Id and another field. I have implemented the equals()/hashcode() override in the POJO for the Id field. When I compare two objects using the equals() method of the Object class, it works perfectly fine. However when I add these objects to an arraylist and implement the

Collections.sort(arrListOfObjects);

它给了我一个classCastexception.我抬起头,发现我需要实现一个比较器.该比较器还执行等于/哈希码替代的操作.如果是这样,那么上面的代码为什么不起作用?(我知道没有比较器,但是我的问题是,是否不可能基于对象的哈希码实现排序?)

it gives me a classCastexception. I looked up and found that I need to implement a Comparator. This comparator also does something to equals/hashcode override. If that is so then why does the above code not work?(I know that there is no comparator, but my question is, is it not possible to implement a sort based on the hashcode of the object?)

推荐答案

如消息所示,您的对象需要实现Comparable接口才能进行排序.另外,您可以为sort()方法提供一个比较器.例如,假设您的对象是字符串,并且要基于哈希码进行排序,则可以执行以下操作:

As the message says, your object needs to implement the Comparable interface to be sortable. Alternatively, you can provide a comparator to your sort() method. For example, assuming your objects are Strings and you want to sort based on hashcodes, you could do this:

public static void main(String[] args) {
    List<String> list = Arrays.asList("string", "sdkj");
    for (String s : list) {
        System.out.println(s + "=" + s.hashCode());
    }
    Collections.sort(list, new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {
            return o1.hashCode() - o2.hashCode();
        }
    });
    System.out.println("After Sorting");
    for (String s : list) {
        System.out.println(s + "=" + s.hashCode());
    }
}

这篇关于使用哈希码对对象的ArrayList进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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