为什么以下代码在调用集合上打印不同的哈希码排序方法请告诉我为什么会出现这种行为?
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);
Run Code Online (Sandbox Code Playgroud)
输出是:
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]
Run Code Online (Sandbox Code Playgroud)
问候
List是有序集合.这意味着List with [1, 2]不等于List [2, 1]也不应该hashCode()相同(理想情况下)
当您对集合进行排序时,您可以更改它的顺序,因此它是hashCode.请注意,这并不是所有类型的保证.例如,所有公式的Long ((x + y) & 0xFFFFFFFF) + y << 32)都具有相同值的hashCode x.这意味着您有一个列表,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());
Run Code Online (Sandbox Code Playgroud)
由于所有Long都使用hashCode为0,因此顺序不会更改hashCode.
923521
923521
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
452 次 |
| 最近记录: |