5

我们都知道,如果我们创建两个 String 对象并使用 == 来比较它们,它将返回 false,如果我们使用 equals 方法,它将返回 true。但是默认情况下 equals 方法只实现 == ,那么它如何返回 true ,它应该返回 == 返回的任何内容?

4

5 回答 5

8

是的,默认情况下等于类==中的方法实现Object。但是你可以在你自己的类中重写equals方法来改变equality同一个类的两个对象之间的方式。例如equals,类中的方法String被覆盖如下:

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;
      }

所以这就是以下代码的原因:

String s1 = new String("java");
String s2 = new String("java");

s1==s2返回false,因为两者都引用了堆上的不同对象。而从现在开始s1.equals(s2)返回的是被调用的是在类中定义的对象,其中对象基于字符串进行比较。trueequalsStringStringcontents

于 2013-03-23T10:17:53.603 回答
1

String 类中的 equals 方法被覆盖,它尝试检查两个字符串中的所有字符是否相等。如果找到,则返回 true。所以 String 类中的 equals 方法的行为与它的普通对象类实现不同。

于 2013-03-23T10:17:30.737 回答
0

Stringjava中的类覆盖了类的equals方法,Object以便比较两个字符串的内容而不是比较引用(Object类中的默认实现)。

下面看类的equals方法实现String

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;
    }
于 2013-03-23T10:27:53.817 回答
0

equals方法原本是Object类的方法。Java 中的每个类都Object默认扩展该类。现在,equals方法被覆盖,String类的行为不同于==.

它的javadoc完美地解释了它:

将此字符串与指定对象进行比较。当且仅当参数不为 null 并且是表示与此对象相同的字符序列的 String 对象时,结果才为真。

它的实现如下:

@override
public boolean equals(Object anObject) {
// This check is just for the case when exact same String object is passed
if (this == anObject) {
    return true;
}
// After this only real implementation of equals start which you might be looking for
// For other cases checks start from here
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;
}
于 2013-03-23T10:16:48.213 回答
0

.equals()检查字符串是否相同 ei。具有相同的字符。==仅检查指针是否指向相同的对象。您可以拥有具有相同字符的不同对象,这就是为什么您应该使用.equals()它们来比较它们

于 2013-03-23T10:18:30.163 回答