Take a look at a piece of code, from Zhou Zhiming's "in-depth understanding of Java virtual machines."
Integer a = 1; Integer b = 2; Integer c = 3; Integer d = 3; Integer e = 321; Integer f = 321; Long g = 3l; System.out.println (c == D); System.out.println (e == f);//There's a integercache-128~127 problem here System.out.println ( c = = (a + b)); System.out.println (C.equals (a + b)); System.out.println (g = = (a + b));//automatic unpacking and automatic packing? System.out.println (G.equals (a + b));//Because both A and B are integer types, the arithmetic operation is an integer type, and long is not a type, so is false, see the source code behind. equals does not deal with the problem of data transformation, the type is different and does not compare values.
Output:
Truefalsetruetruetruefalse
Let's look at the difference between = = and equals in Java:
= = Comparison reference. If the object is not a composite data type but a base type, the comparison is also a value.
Equals is the value that is compared.
Then look at the source of equals in the integer class:
Public Boolean equals (Object obj) { ifinstanceof Integer) { return value = = ((Integer) obj). Intvalue (); } return false ; }
Then look at the author's explanation in the original book:
the "= =" Operation of the wrapper class (referred to as Integer, in contrast to int) does not automatically unpack without encountering arithmetic operations, and their equals () method does not handle the relationship of data transformation.
[Reading notes] auto-boxed traps and = = with equals