问题描述
我正在深入研究Java的基础知识。
我从这个中推断出, java equals方法意味着,如果两个对象相等,那么它们必须具有相同的hashCode()。
I am digging into the basics of Java.I infer from this article, that java equals method means, if two objects are equal then they must have the same hashCode().
这是我的例子。
public class Equals {
/**
* @param args
*/
public static void main(String[] args) {
String a = new String("a");
String b = new String("a");
System.out.println("a.hashCode() "+a.hashCode());
System.out.println("b.hashCode() "+b.hashCode());
System.out.println(a == b);
System.out.println(a.equals(b));
}
}
输出:
a.hashCode()97
b.hashCode()97
false
true
output:
a.hashCode() 97
b.hashCode() 97
false
true
实际Java语言等于方法
Actual Java language equals method
public boolean equals(Object obj) {
return (this == obj);
}
在上面的例子中,a.equals(b)返回true,意思是满足条件a == b。但是为什么a == b在这个例子中返回false?
In my above example, a.equals(b) has returned true, meaning the condition a==b is satisfied. But then why a==b is returning false in that example?
不是hashCode和地址一样吗?
另外,当我们说a == b或其他什么时,hashCode会被比较吗?
Aren't hashCode and address one and same?Also, is hashCode compared when we say a==b or something else?
推荐答案
String
class已重写 equals()
方法。请关注文档。
String
class has overridden the equals()
method . Please follow the String#equals() documentation.
a.equals(b)返回true,表示满足条件a == b
这是对象中
class, equals()
的默认实现 String
class已覆盖默认实现。当且仅当参数不为null并且是表示与此对象相同的字符序列的String对象时,它才返回true。
This is the default implementation of equals()
in the Object
class , String
class has overridden the default implementation. It returns true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
不是hashCode和地址一样吗?
不一定,有关。
这篇关于equals()方法的工作原理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!