java 计算hash_用Java如何计算hashCode()

小编典典

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值