本文主要是介绍Java HasCode equals == 的区别,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
==
用来判断两个值,或者两个对象的内存地址是否一样。
equals
equals 方法用来判断两个对象是否相等。equals 是Object 类的方法,默认情况下,比较两个对象是否是同一个对象,内部通过 == 实现。如果想比较两个对象的其他内容,则可以通过重写equals 方法。比如String 就重写了equals 方法。
equals是Object类的方法,默认情况下比较两个对象是否是同一个对象,内部实现是通过“==”来实现的。
如果想比较两个对象的其他内容,则可以通过重写equals方法,
例如:String类就重写了equals方法,改成了对象的内容是否相等。
hasCode方法:
/*** Returns a hash code value for the object. This method is* supported for the benefit of hash tables such as those provided by* {@link java.util.HashMap}.* <p>* The general contract of {@code hashCode} is:* <ul>* <li>Whenever it is invoked on the same object more than once during* an execution of a Java application, the {@code hashCode} method* must consistently return the same integer, provided no information* used in {@code equals} comparisons on the object is modified.* This integer need not remain consistent from one execution of an* application to another execution of the same application.* <li>If two objects are equal according to the {@code equals(Object)}* method, then calling the {@code hashCode} method on each of* the two objects must produce the same integer result.* <li>It is <em>not</em> required that if two objects are unequal* according to the {@link java.lang.Object#equals(java.lang.Object)}* method, then calling the {@code hashCode} method on each of the* two objects must produce distinct integer results. However, the* programmer should be aware that producing distinct integer results* for unequal objects may improve the performance of hash tables.* </ul>* <p>* As much as is reasonably practical, the hashCode method defined by* class {@code Object} does return distinct integers for distinct* objects. (This is typically implemented by converting the internal* address of the object into an integer, but this implementation* technique is not required by the* Java™ programming language.)** @return a hash code value for this object.* @see java.lang.Object#equals(java.lang.Object)* @see java.lang.System#identityHashCode*/public int hashCode() {return identityHashCode(this);}
hasCode 这个方法会在HasMap 里面使用到。
通常来说,在一次程序运行期间,一个对象的hasCode 是不变的。在不同的程序运行期间可以不同。
如果两个对象的equals的方法返回的值是相等的,那么hasCode 就应该返回一样的值。
不同的对象的hasCode可能是一样的。但是不同对象返回不同hasCode 能够提高has 表的性能。
同一个类,new 出来两个实例,他们俩的hasCode 是不一样的。
这篇关于Java HasCode equals == 的区别的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!