equals()和hashCode()之间的区别 [英] difference between equals() and hashCode()

查看:155
本文介绍了equals()和hashCode()之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个关于equals(),==和hashCode()的简短定义。如果我运行以下代码意味着输出将是true false 2420395 2420395。但我明白equals()方法比较字符串和==比较引用。但是在输出中,hashCcode()方法将两个字符串的引用号打印为相同,然后==返回false。

I want a brief definition about the equals() , "==" and hashCode(). If i run following code means the output will be "true false 2420395 2420395". But i had understand that equals() method compares the string and "==" compares the reference. But in output the hashCcode() method prints the reference number for both strings as same then why the "==" returns "false".

            String str = "Name";
    String str1 = new String("Name");

    if(str.equals(str1))
        System.out.println("true");
    else
        System.out.println("false");
    if(str==str1)
        System.out.println("true");
    else
        System.out.println("false");

    System.out.println(str.hashCode());
    System.out.println(str1.hashCode());
}


推荐答案

等于(当实现这两种方法的对象被添加到集合时, hashCode()方法被证明是非常重要的。如果实施不当,可能会破坏你的生活。

The equals() and hashCode() methods prove to be very important, when objects implementing these two methods are added to collections. If implemented incorrectly it might screwed up your life.

equals():此方法检查是否有一些其他对象作为参数传递给它等于调用此方法的对象。如果你不理解合同,很容易错误地实现equals()方法。在重写此方法之前,需要记住以下属性 -

equals() : This method checks if some other object passed to it as an argument is equal the object in which this method is invoked. It is easy to implement the equals() method incorrectly, if you do not understand the contract. Before overriding this method, following "properties" need to keep in mind -


  • 反身:o1.equals(o1) - 表示对象(例如o1)应该等于它自己

  • 对称:o1.equals(o2)if和only o2.equals(o1)

  • 传递: o1.equals(o2)&& o2.equals(o3)意味着o1.equals(o3)以及

  • 一致:只要o1和o2未被修改,o1.equals(o2)就会返回相同的颜色

  • null比较:!o1.equals(null) - 这意味着任何可实例化的对象都不等于null。因此,如果将null作为参数传递给对象o1,则它应返回false。

  • 哈希代码值:o1.equals(o2)表示o1.hashCode()== o2 .hashCode()。这是非常重要的。如果定义equals()方法,则还必须定义hashCode()方法。此外,它意味着如果你有两个相等的对象,那么它们必须具有相同的hashCode,但反之则不正确

  • Reflexive: o1.equals(o1) - which means an Object (e.g. o1) should be equal to itself
  • Symmetric: o1.equals(o2) if and only o2.equals(o1)
  • Transitive: o1.equals(o2) && o2.equals(o3) implies that o1.equals(o3) as well
  • Consistent: o1.equals(o2) returns the same as long as o1 and o2 are unmodified
  • null comparison : !o1.equals(null) - which means that any instantiable object is not equal to null. So if you pass a null as an argument to your object o1, then it should return false.
  • Hash code value: o1.equals(o2) implies o1.hashCode() == o2.hashCode() . This is very important. If you define a equals() method then you must define a hashCode() method as well. Also it means that if you have two objects that are equal then they must have the same hashCode, however the reverse is not true

来自java源代码

*
* @param   obj   the reference object with which to compare.
* @return  {@code true} if this object is the same as the obj
*          argument; {@code false} otherwise.
* @see     #hashCode()
* @see     java.util.HashMap
*/
public boolean equals(Object obj) {
   return (this == obj);

}

hashCode( ):此方法返回一个hashCode()值作为Integer,并且支持基于散列的java.util.Collection类,如Hashtable,HashMap,HashSet等。如果一个类重写了equals()方法,它也必须实现hashCode()方法。在重写此方法之前,需要记住

hashCode(): This method returns a hashCode() value as an Integer and is supported for the benefit of hashing based java.util.Collection classes like Hashtable, HashMap, HashSet etc. If a class overrides the equals() method, it must implement the hashCode() method as well.Before overriding this method, you need to keep in mind


  • 每当hashCode()方法是在执行Java程序期间,在同一对象上多次调用此方法,此方法必须始终返回相同的结果。从程序的一次执行到同一程序的下次执行,整数结果不需要保持一致。

  • 如果两个对象按照equals()方法相等,那么在两个对象中的每个对象中调用hashCode()方法必须返回相同的整数结果。所以,如果一个字段没有在equals()中使用,那么它不能在hashCode()方法中使用。

  • Whenever hashCode() method is invoked on the same object more than once during an execution of a Java program, this method must consistently return the same result. The integer result need not remain consistent from one execution of the program to the next execution of the same program.
  • If two objects are equal as per the equals() method, then calling the hashCode() method in each of the two objects must return the same integer result. So, If a field is not used in equals(), then it must not be used in hashCode() method.

如果两个对象不相等在equals()方法中,两个对象中的每一个都可以返回两个不同的整数结果或相同的整数结果(即,如果2个对象具有相同的hashCode()结果并不意味着它们是相等的,但如果两个对象相等则那么它们必须返回相同的hashCode()结果。。

If two objects are unequal as per the equals() method, each of the two objects can return either two different integer results or same integer results (i.e. if 2 objects have the same hashCode() result does not mean that they are equal, but if two objects are equal then they must return the same hashCode() result).

根据java源代码
尽管相当实用,java.lang.Object定义的hashCode方法确实为不同的对象返回不同的整数。 (这通常通过将对象的内部地址转换为整数来实现)

As per java source code As much as is reasonably practical, the hashCode method defined by java.lang.Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer)

这篇关于equals()和hashCode()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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