Let's see a test result first:
/*public static void main(String[] args) { Integer a = 128, b = 128; Integer c = 127, d = 127; System.out.println(a == b);//false System.out.println(c == d);//true }*/ /*public static void main(String[] args) { Integer int1 = Integer.valueOf("100"); Integer int2 = Integer.valueOf("100"); System.out.println(int1 == int2);//true }*/ public static void main(String[] args) { Integer int1 = Integer.valueOf("300"); Integer int2 = Integer.valueOf("300"); System.out.println(int1 == int2);//false }The source code of JDK is as follows:
public static Integer valueOf(String s) throws NumberFormatException { return Integer.valueOf(parseInt(s, 10)); }public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }I found that there was another mystery inside, and there was an IntegerCache class:
private static class IntegerCache { static final int low = -128; static final int high; static final Integer cache[]; static { // high value may be configured by property int h = 127; String integerCacheHighPropValue = sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high"); if (integerCacheHighPropValue != null) { try { int i = parseInt(integerCacheHighPropValue); i = Math.max(i, 127); // Maximum array size is Integer.MAX_VALUE h = Math.min(i, Integer.MAX_VALUE - (-low) -1); } catch( NumberFormatException nfe) { // If the property cannot be parsed into an int, ignore it. } } high = h; cache = new Integer[(high - low) + 1]; int j = low; for(int k = 0; k < cache.length; k++) cache[k] = new Integer(j++); // range [-128, 127] must be internalized (JLS7 5.1.7) assert IntegerCache.high >= 127; } private IntegerCache() {} }It turns out that Integer instantiates all integers from -128 to 127 (adjustable).
This explains the answer. It turns out that no matter how many Integers you create in this range, they all use ValueOf to produce the same object.
But why does JDK have to do so much in this way? Let’s think about it carefully. Most of Taobao’s products are priced under 100 yuan. How many Integers will be used in the backend server in one day? Using IntegerCache, it reduces the time to get new and improves efficiency. At the same time, JDK also provides cache high value configurable.
This undoubtedly improves flexibility and facilitates optimization of JVM.
Summarize
The above is all the content of this article about reading the Integer IntegerCache source code, I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!