When comparing objects, you often use "= =" and "Equals (object)." They often make beginners feel puzzled. Let's look at an example
public class Example1
{
public static void Main (string[] args)
{
String S1=new string ("abc");
String S2=new string ("abc");
S1=S2;
System.out.println ("compare the results with = = =");
System.out.println (S1==S2); False
}
}
Since two string objects have the same content as "ABC", Why do you want to make false first? That is because "= =" Compared to two objects of the reference (references), is not their content, how to compare the content is equal? The result of removing the annotation from the s1=s2 sentence is different because they have the same reference.
We use the Equals (object) method, because the Equals (object) method is defined in the object class as a subclass of the class that is defined in the default manner. That is, the object class is a superclass of all classes (superclass, also called the parent class, the base class, and so on), and the Equals (object) method in object is the standard form of
public boolean equals (Object obj)
The return type is Boolean, that is, the True/false is the same as the "= =" return type. The Equals (object) method defined in the object class is two objects that are compared directly with "= =", so that equals (object) and "= =" are not overwritten (override, or rewrite, override) Equals (object) methods. Is the same as the reference to the comparison. The following example (the result is in the note):
public class Example4
{
public static void Main (string[] args)
{
Example4 e=new Example4 ();
Example4 e4=new Example4 ();
System.out.println ("Compare results with Equals (Object)");
System.out.println (E.equals (E4)); The result is false
System.out.println ("compare the results with = = =");
System.out.println (e==e4); The result is false
}
}
The Equals (Object) method is more special than "= =" because it can be overridden, so we can use overlay to make it not a comparison reference but rather a comparison of data content. Of course JDK also has a class that overrides the Equals (object) method, such as Java.lang.String, which overrides the Equals (object) method inherited from Object to compare whether the string content is the same. Take a look at the following example:
public class Example1
{
public static void Main (string[] args)
{
String S1=new string ("abc");
String S2=new string ("abc");
System.out.println ("compare the results with = = =");
System.out.println (S1==S2);//false
System.out.println ("Compare results with Equals (Object)");
System.out.println (s1.equals (S2));//true
}
}
Example to compare the result with equals (Object) to True. Use = = to compare the result to false. The String.Equals (Object) method compares the contents of two strings directly, and returns True if the same, otherwise returns false. You can try to change one of the "ABC" to "ABCDE" to see how the results change.