即日起在codingBlog上分享您的技术经验即可获得积分,积分可兑换现金哦。

Sorting ArrayList of Objects using Hashcode

栈溢出 assylias 153℃ 0评论
本文目录
[隐藏]

1.原始问题:Sorting ArrayList of Objects using Hashcode

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

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?)

2.被采纳答案

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 list = Arrays.asList("string", "sdkj");
    for (String s : list) {
        System.out.println(s + "=" + s.hashCode());
    }
    Collections.sort(list, new Comparator() {

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

3.其他高票答案

3.1.第1个答案

Implementing a sort based on a hash code is certainly possible, but might not consistently produce the behavior desired. For instance, consider a class Foo whose hashCode() method is defined to always return a constant value. For example:

public int hashCode() {
     return 1;
}

Given this hashCode method in tandem with a defined Comparator using this method, lists are almost certain to not be sorted correctly, barring the trivial cases (empty list, single element list, etc.).

In general, a good thing to bear in mind is the hashCode-equals contract documented in the java.lang.Object.hashCode java doc. In a nutshell, it is possible hashCode collisions may result for unequal objects, rendering sorts defined on those methods ineffective.

3.2.第2个答案

Comparator does not do anything to equals or hashcode, it uses equals or hashcode to determine what it returns. It is part of the documentation for the Collections.sort method. Take at look at at
Comparable interface and implement it in your class. You can take a look at the SO Question java class implements comparable for an example.

转载请注明:CodingBlog » Sorting ArrayList of Objects using Hashcode

喜欢 (0)or分享 (0)
发表我的评论
取消评论

*

表情