首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Collections.sort哈希码

Collections.sort哈希码
EN

Stack Overflow用户
提问于 2014-08-18 21:26:45
回答 2查看 537关注 0票数 1

为什么下面的代码在调用集合排序方法时会打印不同的哈希码,请让我知道为什么会出现这种行为?

代码语言:javascript
复制
    List<Integer> list = new ArrayList<>();

    for (int i = 0; i < 10; i++) {

        list.add((int) (Math.random() *100));

    }

    System.out.println("Before List =" + list);

    System.out.println("object hashcode-1 =" + list.hashCode());

    Collections.sort(list);

    System.out.println("In >>> object hashcode-1 =" + list.hashCode());
    Collections.sort(list,new Comparator<Integer>() {

        @Override
        public int compare(Integer o1, Integer o2) {
            return (o1.intValue() > o2.intValue() ?-1:1);
        }
    });
    System.out.println("object hashcode-2 =" + list.hashCode());
    System.out.println("After List =" + list);
    Collections.sort(list,Collections.reverseOrder());
    System.out.println("object hashcode-3 =" + list.hashCode());
    System.out.println("Reverse Order List =" + list);

输出为:

代码语言:javascript
复制
Before List =[58, 12, 38, 36, 56, 78, 65, 70, 51, 63]
object hashcode-1 =545500024
In >>> object hashcode-1 =975071634
object hashcode-2 =1492547664
After List =[78, 70, 65, 63, 58, 56, 51, 38, 36, 12]
object hashcode-3 =1492547664
Reverse Order List =[78, 70, 65, 63, 58, 56, 51, 38, 36, 12]

问候

EN

回答 2

Stack Overflow用户

发布于 2014-08-18 21:30:49

列表是一个有序的集合。这意味着带有[1, 2]的列表不等于列表[2, 1],hashCode()也不应该相同(理想情况下)

当你对集合进行排序时,你改变了它的顺序,因此它是hashCode的。注意,这并不是所有类型的保证种子。例如,对于相同的x值,所有长的公式((x + y) & 0xFFFFFFFF) + y << 32)具有相同的hashCode。这意味着您有一个Long列表,其中每个long具有相同的hashCode,因此这些数字的列表将具有相同的hashCode,而不管顺序如何。

代码语言:javascript
复制
List<Long> l1 = Arrays.asList(-1L, 0L, (1L << 32) + 1, (2L << 32) + 2);
List<Long> l2 = Arrays.asList((2L << 32) + 2, (1L << 32) + 1, 0L, -1L);
System.out.println(l1.hashCode());
System.out.println(l2.hashCode());

因为所有的Long都使用0的hashCode,所以顺序不会改变hashCode。

代码语言:javascript
复制
923521
923521
票数 5
EN

Stack Overflow用户

发布于 2014-08-18 21:30:29

ArrayList#hashCode (实际上是在AbstractList中实现的)根据列表元素的顺序计算散列值:

代码语言:javascript
复制
public int hashCode() {
    int hashCode = 1;
    for (E e : this)
        hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
    return hashCode;
}

您可以看到,在将每个元素的散列代码添加到总数之前,需要将前一个总数乘以31。以不同的顺序添加元素的散列代码将产生不同的结果。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25364506

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档