关于Integer和int类型数据的内存分析
底层代码
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];//缓存数组 -128~127
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 interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
package com.qfedu.c_baozhuang;
public class Demo3 {
public static void main(String[] args) {
Integer i1 = 10;//没有new 直接从常量池中取的
Integer i2 = 10;//没有new 直接从常量池中取的
System.out.println(i1 == i2);//true
Integer i3 = 1000;//new对象了
Integer i4 = 1000;//new对象了
System.out.println(i3 == i4);//false
//考察了Integer类加载的时候,
// 它就创建了自己的静态空间(常量池),
// 立即加载了Integer类型的数组, static final Integer cache[];
// 数组内存储了256个Integer类型的对象-128 - 127,
// 如果我们用的对象范围在这之内,是final修饰的,就意味着不会改变地址
//i1 没有超过-128 ~127这个范围的时候,不会改变地址的,就意味着内存地址是一样的
//使用==的时候,比较内存地址,所以相等!!!
// 如Ingeger i1 = 10;JVM就会直接从静态区的Integer类型的缓冲数组中直接找对应的对象,
// 如果我们用的对象范围超出了这个-128~127,例如Integer i1 = 1000;
// JVM就会帮我们在堆内存中创建一个新的Integer对象。那么内存地址不一样的
// 使用==比较的就是一个false
}
}
京东面试题:
Integer i1 = 10;
Intger i2 = 10;
sout(i1 == i2);//true 不会创建新的对象,直接从常量池
Integer i3 = 1000;
Integer i4 = 1000;
sout(i3 == i4);//false 已经超过缓存数组的容量了-128~127 ,就要在堆区去创建新的对象了
总结:
int类型赋值:不管值的大小,都在常量池中!!!
int a= 128; int a = 8999; 都在常量池中!!!
Integer类型赋值:
Integer i1 = 10;//不会在堆区创建对象
Integer i2 = 1000;//堆区会创建对象,值会指向常量池中的那个值!!!
若值的范围在-128~127之间,在常量池中!!!
如果值的范围不在-128~127之间,则在堆区创建对象,进行赋值了
实例化Integer对象:
Integer i1 = new Integer(12);
只要是new的Integer 使用== 都是false
9.png