为什么下面的代码在调用集合排序方法时打印不同的哈希码 请告诉我为什么会出现这种行为?
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);
输出是:
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]
问候
最佳答案
List 是一个有序的集合。这意味着带有 [1, 2]
的列表不等于列表 [2, 1]
hashCode() 也不应该相同(理想情况下)
当你对集合进行排序时,你改变了它的顺序,因此它是 hashCode。请注意,这并不能保证所有类型。例如所有 Long 的公式 ((x + y) & 0xFFFFFFFF) + y << 32)
x
的相同值具有相同的 hashCode .这意味着您有一个列表 Long
其中每个 long 具有相同的 hashCode,因此无论顺序如何,这些数字的列表都将具有相同的 hashCode。
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。
923521
923521
关于java - Collections.sort 哈希码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25364506/