Look at the code first, and run the results
public static void Main (string[] args) {System.out.println ("object comparison"); String Str1=new string ("str"); String Str2=new string ("str"); System.out.println ("= = comparison" + (STR1==STR2)); System.out.println ("Equal comparison" +str1.equals (STR2)); System.out.println ("Value comparison"); String str3= "str1"; String str4= "str1"; System.out.println ("= = comparison" + (STR3==STR4)); System.out.println ("Equal comparison" +str3.equals (STR4));}
The result of the output is:
According to the printing can be found using equal comparison whether using automatic boxing to instantiate or with new to instantiate, return is true, and with = = is not the same, automatic boxing to instantiate the return is true, and new to instantiate the return of real false; The first to solve why, first to understand the difference between equals and = =, then you can know the answer
The Equals method is initially defined in the base class object of all classes, and the source code is
public boolean equals (Object obj) { return (this = = obj);}
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; }
after rewriting equal and = = has the essential difference:
equal: is used to compare whether the contents of two objects are equal, because all classes inherit from the Java.lang.Object class, so if the method is not overwritten, the
any meaning.
==: is used to determine whether the address of two objects is the same, that is, whether it refers to the same object. The comparison is in the real sense of the pointer operation.
Note: the definition of equals and hashcode must be consistent: if X.equals (y) returns True, then X.hashcode () must have the same value as Y.hashcode ()
The difference between = = and equal in Java