Interesting exploration of the '=' and 'equals () 'methods in java
In the past two days, I have benefited a lot from Zhou Zhiming's "deep understanding of java Virtual Machine". Based on the inspiration in the book, '=' and 'equals () 'The difference between methods has been explored.
First of all, in order to get into the status more quickly, let's take a look at the following examples. The routine is as follows. Please judge the output results of each System. out. println.
public static void main(String[] args) { 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); System.out.println(c==(a+b)); System.out.println(c.equals(a+b)); System.out.println(g==(a+b)); System.out.println(g.equals(a+b)); }
The output result is as follows:
truefalsetruetruetruefalse
I have received some explanations on the Internet:
1. The basic data type, also known as the original data type. Byte, short, char, int, long, float, double, boolean
Apply the equal sign (=) to compare their values.
2. composite data types (classes), when compared with (=), compare their storage addresses in the memory, for Integer, String, Long .... and so on. The value is compared due to the packing process.
3. the default Implementation of equals in the Object class is the same as =. For Integer, String, Long .... and so on.
Next we will explain the output results using the above explanations: Here, interpretation 2 can explain the output of rows 1st, 3, and 5, but it can explain the output of rows 2nd; Interpretation 3 can explain the output of rows 4th, but it cannot explain 6th rows of output. Next we will answer the question step by step.
Question 1: Why is true returned when two Integer objects with a value of 3 Use = for comparison, while an Integer object with the same value of 321 is false at =?
Since you use = to compare the address of an Integer object in the memory, we can see how the compiled bytecode identifies an Integer variable, are the symbolic references of these two objects the same?
Use the built-in jdk javap tool to output the class file of the routine in the format and extract the following fragments:
10: iconst_3 11: invokestatic #16 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer; 14: astore_3 15: iconst_3 16: invokestatic #16 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer; 19: astore 4
The above bytecode command corresponds to 'integer c = 3; Integer d = 3; 'in java code, iconst_1 refers to pressing constant 1 into the operand stack, the invokestatic command calls the valueOf (int I) method of the Integer class, uses constant 1 as its parameter, and uses Integer. valueOf (1) is used as the result to put the 1st slots (memory unit) in the local variable table ). The bytecode shows that the jvm calls Integer twice at runtime. the valueOf () method initializes the c and d variables. Let's look at Integer. the implementation of the valueOf () method.
public static Integer valueOf(int i) { if(!$assertionsDisabled && IntegerCache.high < 127) throw new AssertionError(); if(i >= -128 && i <= IntegerCache.high) return IntegerCache.cache[i + 128]; else return new Integer(i); }$ AssertionsDisabled variable literal understanding should be asserted unavailable, plus! It should be asserted to be available (to be verified ). IntegerCache. high <127, decompile the internal IntegerCache code:
private static class IntegerCache { static final int low = -128; static final int high; static final Integer cache[]; static { int i = 127; String s = VM.getSavedProperty("java.lang.Integer.IntegerCache.high"); if(s != null) { int j = Integer.parseInt(s); j = Math.max(j, 127); i = Math.min(j, 2147483519); } high = i; cache = new Integer[(high - -128) + 1]; int k = -128; for(int l = 0; l < cache.length; l++) cache[l] = new Integer(k++); } private IntegerCache() { } }
IntegerCache found. the high value depends on 'java. lang. integer. integerCache. the value range of high 'jvm parameter settings is [128, 2147483519]. Therefore, the first if statement is skipped in most cases. Then, let's look at the second if statement, when I is in [-, IntegerCache. high], the value in the mixed village cache will be used. At this time, no matter how many calls Integer. valueOf (int I), as long as the input I is the same, the returned object reference is one; otherwise, it is not one. So we can guess that IntegerCache. high should be set to 127 by default. This explains why true is returned when two Integer objects whose values are 3 Use = for comparison, while the Integer object whose values are the same as 321 returns false when =.
If we adjust the jvm parameter "java. lang. Integer. IntegerCache. high" to 321, the = comparison of 321 should also return true. Therefore, many questions are not required ~
Conclusion: In the default jvm settings, if the value of an Integer object with a value of [-128,127] is initialized using valueOf () (such as Integer a = 2; or Integer B = Integer. valueOf ("3");), the object references the same, = returns true, and Integer objects outside the range do not meet this rule;
You can change the maximum value of the interval by setting the jvm parameter "java. lang. Integer. IntegerCache. high;
The valueOf (Long l) Implementation of Short. java and long. java writes the interval to [-128,127];
The valueOf () Methods of Double. java and Float. java are implemented using the new object method. Therefore, the above rules are not applicable.
Question 2: Why is false returned if the Long and Integer objects with the same value use =?
This is relatively simple. Let's look at the implementation of the equals () Methods of Long. java and Integer. java.
Implementation of Long. java's equals method:
public boolean equals(Object obj) { if(obj instanceof Long) return value == ((Long)obj).longValue(); else return false; }
Implementation of the equals method of Integer. java:
public boolean equals(Object obj) { if(obj instanceof Integer) return value == ((Integer)obj).intValue(); else return false; }
The above code is clear at a glance: The equals method does not support type conversion, so the output of the last line in the routine is false.
Conclusion: The equals method is overwritten for the packing type corresponding to the basic type so that the value is compared, rather than the memory address;
However, the equals method does not support data type conversion after rewriting.
We strongly recommend that you take a look at some of the underlying implementation of jvm, and you will have a deeper understanding of the past.