The Integer.valueOf() method is implemented as follows:

The method is implemented as follows: public static Integer valueOf(int i) {
	final int offset = 128;
	if (i >= -128 && i <= 127) { // must cache
		return IntegerCache.cache[i + offset];
	}
	return new Integer(i);
}


The Integer.valueOf() method caches numbers between [-128, 127] based on the consideration of reducing the number of object creations and saving memory. Passing parameters within this number range directly returns the object in the cache. In addition, directly new out.
Implementation of IntegerCache:

private static class IntegerCache {
	private IntegerCache(){}
	static final Integer cache[] = new Integer[-(-128) + 127 + 1];
	static {
	    for(int i = 0; i < cache.length; i++)
		cache[i] = new Integer(i - 128);
	}
}


test code
true
false
true
true

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326848543&siteId=291194637