Equals () method, equals Method
The equals () method is a method in the root class Object. The subclass can rewrite this method as needed (for example, the String class ).
1. Implement the equals () method in the Object class as follows:
1 public boolean equals(Object obj) {2 return (this == obj);3 }
Example:
1 package com. mianshi. easy; 2 3 class A {} 4 5 public class Equals {6 7 public static void main (String [] args) {8 A a1 = new (); 9 A a2 = new A (); 10 A a3 = a2; 11 System. out. println (a1.equals (a2); 12 System. out. println (a3.equals (a2); 13} 14} 15 16 Result: 17 false18 trueView Code
By default, Class A inherits from the Object class. Therefore, it has the equals () method modified by the public in the parent class and has the same functions.
The function implemented by this method is to compare whether two objects are the same object and return true for the same object. Otherwise, false is returned. Equals () compares the address value of the object stored in obj, which is the same as "=.
II. The equals () method in the String class is implemented as follows:
1 public boolean equals (Object anObject) {2 if (this = anObject) {// first compare whether two objects are the same Object 3 return true; 4} 5 if (anObject instanceof String) {6 String anotherString = (String) anObject; 7 int n = value. length; 8 if (n = anotherString. value. length) {// compare whether the values of the two objects are the same. If the values are the same, equals () returns true 9 char v1 [] = value; 10 char v2 [] = anotherString. value; 11 int I = 0; 12 while (n --! = 0) {13 if (v1 [I]! = V2 [I]) 14 return false; 15 I ++; 16} 17 return true; 18} 19} 20 return false; 21}
Example:
1 package com. mianshi. easy; 2 3 public class Equals {4 5 public static void main (String [] args) {6 String a1 = new String ("Hello "); 7 String a2 = new String ("Hello"); 8 String a3 = "Hello"; 9 // a1 and a2 are obviously not an object, but equals () returns true10 System. out. println (a1.equals (a2); 11 // a1 and a3 are not the same object. equals () returns true12 System. out. println (a3.equals (a1); 13} 14} 15 16 Result: 17 true18 trueView Code
It indicates that the equals () method of the parent class Object is overwritten in the String class. After rewriting, it compares whether the content of the two String objects is the same, and true if the content is the same.