小编典典
hashCode()绝对不能保证由返回的值是对象的内存地址。我不确定Object该类中的实现,但是请记住,大多数类都将覆盖,hashCode()这样两个在语义上等效(但不是同一实例)的实例将散列为相同的值。如果可以在依赖于hashCode与的其他数据结构(例如Set)中使用这些类,则这尤其重要equals。
无论如何hashCode(),都不能唯一地标识对象的实例。如果你想要基于基础指针的哈希码(例如在Sun的实现中),请使用System.identityHashCode()-这将委托给默认hashCode方法,而不管其是否已被覆盖。
尽管如此,甚至System.identityHashCode()可以为多个对象返回相同的哈希值。请参阅注释以获取解释,但这是一个示例程序,该程序连续生成对象,直到找到具有相同对象的两个System.identityHashCode()。当我运行它时,System.identityHashCode()在将大约86,000个Long包装器对象(以及该键的整数包装器)添加后,它很快就会找到两个匹配的。
public static void main(String[] args) {
Map map = new HashMap<>();
Random generator = new Random();
Collection counts = new LinkedList<>();
Long object = generator.nextLong();
// We use the identityHashCode as the key into the map
// This makes it easier to check if any other objects
// have the same key.
int hash = System.identityHashCode(object);
while (!map.containsKey(hash)) {
map.put(hash, object);
object = generator.nextLong();
hash = System.identityHashCode(object);
}
System.out.println("Identical maps for size: " + map.size());
System.out.println("First object value: " + object);
System.out.println("Second object value: " + map.get(hash));
System.out.println("First object identityHash: " + System.identityHashCode(object));
System.out.println("Second object identityHash: " + System.identityHashCode(map.get(hash)));
}
输出示例:
Identical maps for size: 105822
First object value: 7446391633043190962
Second object value: -8143651927768852586
First object identityHash: 2134400190
Second object identityHash: 2134400190
2020-03-22