Object--hashCode()
hashCode()

1 /** 2 * Returns a hash code value for the object. This method is 3 * supported for the benefit of hash tables such as those provided by 4 * {@link java.util.HashMap}. 5 * <p> 6 * The general contract of {@code hashCode} is: 7 * <ul> 8 * <li>Whenever it is invoked on the same object more than once during 9 * an execution of a Java application, the {@code hashCode} method 10 * must consistently return the same integer, provided no information 11 * used in {@code equals} comparisons on the object is modified. 12 * This integer need not remain consistent from one execution of an 13 * application to another execution of the same application. 14 * <li>If two objects are equal according to the {@code equals(Object)} 15 * method, then calling the {@code hashCode} method on each of 16 * the two objects must produce the same integer result. 17 * <li>It is <em>not</em> required that if two objects are unequal 18 * according to the {@link java.lang.Object#equals(java.lang.Object)} 19 * method, then calling the {@code hashCode} method on each of the 20 * two objects must produce distinct integer results. However, the 21 * programmer should be aware that producing distinct integer results 22 * for unequal objects may improve the performance of hash tables. 23 * </ul> 24 * <p> 25 * As much as is reasonably practical, the hashCode method defined by 26 * class {@code Object} does return distinct integers for distinct 27 * objects. (This is typically implemented by converting the internal 28 * address of the object into an integer, but this implementation 29 * technique is not required by the 30 * Java™ programming language.) 31 * 32 * @return a hash code value for this object. 33 * @see java.lang.Object#equals(java.lang.Object) 34 * @see java.lang.System#identityHashCode 35 */ 36 public native int hashCode();
返回这个对象哈希码的值,支持这种方法是为了方便使用哈希表 --比如java.util.HashMap。
下面是hashCode约定的内容:
(1)在应用程序的执行期间,只要对象的equals方法的比较操作所用到的信息没有被修改,那么对同一个对象调用多次,hashCode方法都必须始终如一地返回同一个整数。在同一个应用程序的多次执行过程中,每次执行所返回的整数可以不一致。
(2)如果两个对象根据equals(Object)方法比较是相等的,那么在两个对象上分别调用hashCode()必须产生相同的整数结果。
(3)没有要求说如果两个对象根据equal()方法比较是不相等的,那么在两个对象上分别调用hashCode()产生的整数结果一定不相等。但是,程序员应该意识到,为不相等的对象产生不同的整数结果可以提高散列表的性能。
为了尽可能的实用,Object定义的hashCode方法,对于不同的对象返回的是不同的整数值(这通常是通过将对象的内部地址转换为整数来实现的,但是并非是由Java语言技术实现的)。
感谢您的阅读,如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮。本文欢迎各位转载,但是转载文章之后必须在文章页面中给出作者和原文连接。
希望本文章对您有帮助,您的转发、点赞是我的创作动力,十分感谢。更多好文推荐,请关注我的微信公众号--JustJavaIt
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
2020-08-03 实战Git命令(界面操作+命令行)