为什么对象的Hashcode会在Java中发生变化? [英] Why does the Hashcode of an Object change in Java?

查看:319
本文介绍了为什么对象的Hashcode会在Java中发生变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么对象的Hashcode会在Java中发生变化?它有变化吗?
如何与Hashtable相关?
每个对象都应该拥有它唯一的hashcode.So,是否正在重新说明它的原因?

Why does the Hashcode of an Object change in Java? Does it change at all? How is it related to Hashtable ? Every object should have it's unique hashcode.So, is Rehashing a reason for it ?

提前致谢。

推荐答案

哈希码的默认实现等同于对象标识。但是,某些对象会覆盖哈希码,这可能会为您提供基于对象状态更改的哈希码。

The default implementation of hashcode is equivalent to object identity. However, some objects override hashcode, which might give you a hashcode that changes based on object state.

通常,如果要覆盖equals的定义,则执行此操作事实上,如果你重写equals你应该覆盖hashcode)。这是因为您希望通过您创建的任何定义相等的对象返回相同的哈希码。否则你可能会遇到一个地图包含多个相等对象的情况,因为它们返回不同的哈希码。

Usually you do this if you're overriding the definition of equals( in fact, if you override equals you should override hashcode). This is because you want objects that are equal by whatever definition you've created to return the same hashcode. Otherwise you can have a situation a map holds multiple "equal" objects, because they return different hashcodes.

这篇关于为什么对象的Hashcode会在Java中发生变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆