Question 1 Comparison Between the equals method in the String class and the Object class, objectequals
1. equals method in String
String s1 = "String"; String s2 = "String"; System.out.println(s1.equals(s2));
Result: true
The equals method in the String class overrides the equals method in the Object class.
Compares this string to the specified object. The result istrueIf and only if the argument is notnullAnd isStringObject that represents the same sequence of characters as this object. (String equals method API reference)
Compares the string with the specified object. If and only if this parameter is notnullAnd the object represents the same Character SequenceStringThe result istrue. (String equals method Chinese API Documentation)
2. equals method in Object class
1 Name n1 = new Name("f1","l1"); 2 Name n2 = new Name("f1","l1"); 3 System.out.println(n1.equals(n2)); 4 5 class Name { 6 private String fistname, lastname; 7 8 public Name(String fistname, String lastname) { 9 this.fistname = fistname;10 this.lastname = lastname;11 }12 13 public String GetFistName() {14 return fistname;15 }16 17 public String GetLastName() {18 return lastname;19 }20 21 public String toString() {22 return fistname + " " + lastname;23 }
Result: false
Perform equals comparison between new objects. If the equals method is not rewritten, the comparison between them is based on the address they store in the memory, so the output above is false.
So how do I rewrite equals if they want to make the output result true?
Good. Please refer to the following code:
Name n1 = new Name ("f1", "l1"); Name n2 = new Name ("f1", "l1"); System. out. println (n1.equals (n2); class Name {private String fistname, lastname; public Name (String fistname, String lastname) {this. fistname = fistname; this. lastname = lastname;} public String GetFistName () {return fistname;} public String GetLastName () {return lastname;} public String toString () {return fistname + "" + lastname ;} public boolean equals (Object obj) {if (obj instanceof Name) {// determine whether obj is Name type Name = (name) obj; // because the access Name is a unique member, you need to replace obj with Name class return (fistname. equals (name. fistname) & lastname. equals (name. lastname); // determines whether the specific content is equal} return super. equals (obj );}
Result: true
Here, the equals method of the Object class is overwritten.