问题描述
我们都知道如果我们创建两个String对象并使用==进行比较,它们将返回false,如果我们使用equals to方法将返回true.但是默认情况下,仅等于方法实现==,那么它如何返回true,它应该返回==返回的所有内容?
We all know if we create two String objects and use == to compare them it will return false and if we use equals to method it will return true. But by default equals method implement == only , then how does it return true , it should return whatever == is returning ??
推荐答案
默认情况下,是的equals方法在 Object
类中实现 ==
.但是,您可以在自己的类中覆盖 equals
方法,以更改在同一类的两个对象之间完成 quality
的方式.例如, String
类中的 equals
方法被覆盖如下:
Yes by default equals method implements ==
in Object
class . But you can Override the equals
method in your own class to change the way equality
is done between two objects of the same class. For example the equals
method in String
class is overridden as follows:
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
这就是以下代码的原因:
So this is the reason that for the following code:
String s1 = new String("java");
String s2 = new String("java");
s1 == s2
返回 false
,因为两者都在堆上引用了不同的对象.而 s1.equals(s2)
返回 true
,因为现在调用的 equals
是 String
类中定义的内容,其中根据字符串的内容
比较 String
对象.
s1==s2
returns false
since both are referencing different objects on heap. Whereas s1.equals(s2)
returns true
since now the equals
being called is what defined within String
class where String
objects are compared on the basis of contents
of String.
这篇关于java中的default equals实现如何用于String?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!