包装类:
八个 包装类:
Integer
自动装箱的原理:
`Integer i = 10`
这个代码为什么正确,Integer是一个对象,10是一个int,就是因为:
默认的编译器给你进行了封装:
Integer i = 10;
Integer i = new Integer.valueof(10);
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);}
new Integer(数字)的原理:
在Integer这个类中定义了一个属性value,new的时候把形参的值赋值给了属性value
private final int value;
public Integer(int value) {
this.value = value;
}
自动拆箱原理
把类属性的value值返回,就是自动拆箱;
private final int value;
public int intValue() {
return value;
}
其他类型的自动拆箱
public long longValue() { return (long)value;}
public float floatValue() { return (float)value;}
..........
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);}
在上边这个代码中,有一个注意点:IntegerCache,包装类的一个缓存,他是一个范围
IntegerCache.low => IntegerCache.high,在类中是这样定义的:
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 interned (JLS7 5.1.7)
assert IntegerCache.high >= 127; }
}
他是声明了最小值(-128),定义了Integer类型的数组(cache[]),静态代码块中定义了最高值 127,
然后通过一系列的骚操作,在cache数组添加了数据(-128~127)的数据,组成了所谓的缓存,当需要的
数值在这个范围内时,就会从这个数组中取值,所以取的永远是一个对象。超过这个范围的数,会在堆中
新创建一个对象。
自定义MyInteger
public class MyInteger {
private int value;
private static final int LOW=-128;
private static final int HIGHT=127;
private static MyInteger[] cache;
static {
cache = new MyInteger[HIGHT-LOW+1];
int j=LOW;
for(int i=0;i<cache.length;i++){
cache[i]=new MyInteger(j++);
}
}
public static MyInteger valueof(int value){
if(value>=LOW&&value<=HIGHT){
return MyInteger.cache[value-LOW];
}
return new MyInteger(value);
}
private MyInteger(int value){
this.value = value;
}
public int intValue(){
return value;
}
public static void main(String[] args) {
MyInteger myInteger = MyInteger.valueof(488);
MyInteger myInteger1 = MyInteger.valueof(488);
int a = myInteger.intValue();
System.out.println(a);
System.out.println(myInteger);
System.out.println(myInteger1);
}
}