package Test;
/**
* 自动装箱:
* 基本类型的数据处于需要对象的环境中时,会自动转为“对象”。
* 我们以Integer为例:在JDK1.5以前,这样的代码Integer i=5是错误的
* 必须要通过Integer i=new Integer(5)这样的语句来实现基本数据类型转换
* 成包装类的过程,而在JDK1.5以后,Java提供了自动装箱的功能
* 因此只需Integer i=5这样的语句就能实现基本数据类型转换成包装类
* 这是因为JVM为我们执行了Integer i=Integer.valueOf(5)这样的
* 操作,这就是Java的自动装箱。
* 自动拆箱:
* 每当需要一个值时,对象会自动转成基本数据类型,没必要在去显示调用intValue()
* doubleValue()等转型方法。
* 如Integer i=5;int j=i;这样的过程就是自动拆箱。
* 我们可以用一句话总结自动装箱/拆箱:
* 自动装箱过程是通过调用包装类valueOf()方法实现的,而自动拆箱过程是通过调用
* 包装类的xxxValue()方法实现的(xxx代表对应的基本数据类型,如intValue()/doubleValue()等)
* @author pmc
*
*/
public class PackClassAuto {
public static void main(String[] args){
Integer a=234; //Integer.valueOf(234) 自动装箱
int b=a; //a.intValue() 自动拆箱
}
}
package Test;
//import java.lang.Integer.IntegerCache;
/**
* 自动装箱:
* 基本类型的数据处于需要对象的环境中时,会自动转为“对象”。
* 我们以Integer为例:在JDK1.5以前,这样的代码Integer i=5是错误的
* 必须要通过Integer i=new Integer(5)这样的语句来实现基本数据类型转换
* 成包装类的过程,而在JDK1.5以后,Java提供了自动装箱的功能
* 因此只需Integer i=5这样的语句就能实现基本数据类型转换成包装类
* 这是因为JVM为我们执行了Integer i=Integer.valueOf(5)这样的
* 操作,这就是Java的自动装箱。
* 自动拆箱:
* 每当需要一个值时,对象会自动转成基本数据类型,没必要在去显示调用intValue()
* doubleValue()等转型方法。
* 如Integer i=5;int j=i;这样的过程就是自动拆箱。
* 我们可以用一句话总结自动装箱/拆箱:
* 自动装箱过程是通过调用包装类valueOf()方法实现的,而自动拆箱过程是通过调用
* 包装类的xxxValue()方法实现的(xxx代表对应的基本数据类型,如intValue()/doubleValue()等)
* @author pmc
*
*/
public class PackClassAuto {
public static void main(String[] args){
Integer a=234; //Integer.valueOf(234) 自动装箱
int b=a; //a.intValue() 自动拆箱
/**
* 缓存【-128,127】之间的数字
* 系统初始的时候创建了[-128,127]之间的一个缓存数组
*/
Integer in1=Integer.valueOf(-128);
Integer in2=Integer.valueOf(-128);
System.out.println(in1==in2);//true 在缓存范围内
Integer in3=Integer.valueOf(1234);
Integer in4=Integer.valueOf(1234);
System.out.println(in3==in4);//false 不再缓存范围内
System.out.println(127-(-128));//(127+(-1*-128))=(255)
ss s6=new ss();
System.out.println(ss.valueOf(127));
}
/**
* 源码,假设传入127
* @author pmc
*
*/
public static class ss{
static final int low = -128;
static final int high;
static final Integer cache[];
static{
high = 127;
cache = new Integer[(high - low) + 1];
int j = low;//-128
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);//cache[255]=new Interger(-128+255),等于new Integer(127)
// range [-128, 127] must be interned (JLS7 5.1.7)
assert ss.high >= 127;
}
private ss() {}
public static Integer valueOf(int i) {
if (i >= ss.low && i <= ss.high)//127<=127
return ss.cache[i + (-ss.low)];//[127+(-(-128))]=[255],cache[255]=new Integer(127),返回127这个对象
return new Integer(i);
}
}
}