Java equals() 和 hashCode() 的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24446763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
difference between equals() and hashCode()
提问by Dhivakar
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".
我想要一个关于 equals() 、“==”和 hashCode() 的简要定义。如果我运行以下代码意味着输出将是“true false 2420395 2420395”。但我知道equals() 方法比较字符串,而“==”比较引用。但是在输出中,hashCcode() 方法将两个字符串的参考编号打印为相同的,然后为什么“==”返回“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());
}
回答by Martin Dinov
hashCode()
does not return the object's reference, but a hash of the object, computed in some way. ==
does not compare objects using the value of hashCode()
but, as you correctly say, by the value of the objects' references.
hashCode()
不返回对象的引用,而是以某种方式计算的对象的哈希值。==
不使用 的值比较对象,hashCode()
但正如您所说的那样,通过对象引用的值进行比较。
回答by Pablo Lozano
You can read the hashCode documentation. In a few words it says that if (obj1.equals(obj2)
is truethen obj1.hashCode()==obj2.hasCode()
must be trueto be a valid implementation.
您可以阅读hashCode 文档。简而言之,它表示如果(obj1.equals(obj2)
为真,则obj1.hashCode()==obj2.hasCode()
必须为真才能成为有效的实现。
Note that it does not mean that two different objects cannot share the same hash code. Actually, this example is a valid (but awful) implementation of the method:
请注意,这并不意味着两个不同的对象不能共享相同的哈希码。实际上,这个例子是该方法的一个有效(但很糟糕)的实现:
class MyClass {
public int hashCode() {return 0;}
}
回答by ctzdev
.equals()
compares the actual content of the string.
.equals()
比较字符串的实际内容。
The "==" operator compares if the two objects are the same reference in memory. If you were to do str = str1;
, then the double-equals operator would return true
because they point to the same reference in memory.
“==”运算符比较两个对象是否在内存中是相同的引用。如果您要这样做str = str1;
,那么双等号运算符将返回,true
因为它们指向内存中的相同引用。
hashCode()
returns a hash of the object in an arbitrary manner. The value returned will always be unique as long as the method is not overridden in some way. If .equals()
returns true, the hash code should be the same.
hashCode()
以任意方式返回对象的哈希值。只要该方法未被以某种方式覆盖,返回的值将始终是唯一的。如果.equals()
返回 true,则哈希码应该相同。
回答by Rad
- As other said '==' compares references. But the two methods are just methods doing something which can be overridden.
- Every method does something. If you want to know what it exactly does and what is its meaning you need to read the documentation.
- You may override those methods in anyway you want. But please note that you must follow JAVA documentation for these two methods. Because they are used by other classes. For example
equals()
is used while you try find an object in a list and.hashCode()
is used in some hashtable classes provided by JAVA class library.
- 正如其他人所说的 '==' 比较引用。但是这两种方法只是做一些可以被覆盖的方法。
- 每种方法都会有所作为。如果你想知道它到底做了什么以及它的含义是什么,你需要阅读文档。
- 您可以随意覆盖这些方法。但请注意,这两种方法必须遵循 JAVA 文档。因为它们被其他类使用。例如
equals()
,当您尝试在列表中查找对象时.hashCode()
使用,并在 JAVA 类库提供的一些哈希表类中使用。
回答by dgm
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()和hashCode()方法被证明是非常重要的。如果实施不当,可能会毁了你的生活。
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 -
equals():此方法检查作为参数传递给它的其他对象是否等于调用此方法的对象。如果您不理解合约,很容易错误地实现 equals() 方法。在覆盖这个方法之前,需要记住以下“属性”——
- 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
- 自反:o1.equals(o1) - 这意味着一个对象(例如 o1)应该等于它自己
- 对称:o1.equals(o2) 当且仅 o2.equals(o1)
- 传递性: o1.equals(o2) && o2.equals(o3) 也意味着 o1.equals(o3)
- 一致:o1.equals(o2) 返回相同,只要 o1 和 o2 未修改
- null 比较:!o1.equals(null) - 这意味着任何可实例化的对象都不等于 null。因此,如果您将 null 作为参数传递给对象 o1,则它应该返回 false。
- 哈希码值: o1.equals(o2) 意味着 o1.hashCode() == o2.hashCode() 。这是非常重要的。如果您定义了一个 equals() 方法,那么您还必须定义一个 hashCode() 方法。这也意味着,如果您有两个相等的对象,那么它们必须具有相同的 hashCode,但反之则不然
From java source code
来自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(): 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():此方法返回一个 hashCode() 值作为整数,并且支持基于散列的 java.util.Collection 类,如 Hashtable、HashMap、HashSet 等。如果一个类覆盖了 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.
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 程序执行期间,只要在同一对象上多次调用 hashCode() 方法,此方法必须始终返回相同的结果。从程序的一次执行到同一程序的下一次执行,整数结果不需要保持一致。
如果根据 equals() 方法两个对象相等,则在两个对象中的每一个中调用 hashCode() 方法必须返回相同的整数结果。因此,如果某个字段未在 equals() 中使用,则不得在 hashCode() 方法中使用它。
如果根据 equals() 方法两个对象不相等,则两个对象中的每一个都可以返回两个不同的整数结果或相同的整数结果(即如果两个对象具有相同的 hashCode() 结果并不意味着它们相等,而是如果两个对象相等,则它们必须返回相同的 hashCode() 结果)。
As per java source codeAs 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)
根据 java 源代码在合理可行的情况下,java.lang.Object 定义的 hashCode 方法确实为不同的对象返回不同的整数。(这通常是通过将对象的内部地址转换为整数来实现的)
回答by Amit Yadav
equals() only compare string it's does not check reference of string
equals() 只比较字符串,它不检查字符串的引用
but '==' check reference and data both
但是'=='检查参考和数据
in 1st case String str = "Name"; only one object is created but in
在第一种情况下 String str = "Name"; 只创建了一个对象,但在
2nd case Two object is created
第二种情况创建了两个对象
String str1 = new String("Name");
then reference are not same of both string that means it returns false
那么两个字符串的引用都不相同,这意味着它返回 false
回答by 0coder
equals() and hashCode() are different methods and hashCode method should not be used to check if two object references are same. Reason:hashCode just returns int value for an Object, even two different objects can have same hashCode integer. The value returned by hashCode() is the object's hash code, which is the object's memory address in hexadecimal. equals()checks if the two object references are same. If two objects are equal then their hashCode must be the same, but the reverse is not true.
equals() 和 hashCode() 是不同的方法,不应使用 hashCode 方法来检查两个对象引用是否相同。 原因:hashCode 只是返回一个对象的 int 值,即使两个不同的对象也可以具有相同的 hashCode 整数。hashCode() 返回的值是对象的哈希码,也就是对象的十六进制内存地址。 equals()检查两个对象引用是否相同。如果两个对象相等,则它们的 hashCode 必须相同,反之则不然。