How is the default value equal to the implementation in java files for String?

We all know whether we create two String objects and use == to compare them, it will return false, and if we use the equals to method, it will return true. But by default it is equivalent to the method implementation method ==, whereas it returns true, it should return the return value ==

+5
source share
5 answers

Yes, by default the equals method implements ==in the class Object. But you can override the method equalsin your own class to change the way equalitybetween two objects of the same class. For example, a method equalsin a class is Stringredefined 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;
      }

, , :

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

s1==s2 false, . s1.equals(s2) true, equals, String, String contents String.

+7

equals String , . , true. , equals String .

+1

equals Object. Java Object . equals String, , ==.

javadoc :

. true , 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;
}
0

.equals() , ei. . == , . , .equals().

0

String java 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;
    }
0
source

All Articles