一、分析
包装类型产生对象的两种方式:
1.new产生的Integer对象
new声明的就是要生成一个对象,没二话,这就是两个对象,地址肯定不相等。
2.装箱生成的对象
装箱动作是通过valueOf()方法实现的,我们阅读以下Integer.valueOf的实现代码:
[java]view plaincopy
1 publicstatic Integer valueOf(int i){
2 finalint offset = 128;
3 if(i >= -128 && i <= 127){
4 return IntegerCache.cache(i + offset);
5 }
6 retrun new Integer(i);
7 }<span style="background-color: transparent; color: windowtext; font-size: 10pt; font-family: Calibri, sans-serif;"> </span>
这段代码,如果是-128至127之间的int类型转换为Integer对象,则直接从cache数组中获得,代码如下:
[java]view plaincopy
8 staticfinal Integer cache[] = new Integer[-(-128) + 127 + 1];
9 static{
10 for(int i = 0; i < cache.length; i++){
11 cache[i] = new Integer(i-128);
12 }
13 }
cache是IntegerCache内部类的一个静态数组,容纳的是-128到127之间的Integer对象,通过valueOf产生包装对象时,如果int参数在-128和127之间,则直接从×××池中获得对象,不在该范围的int类型则通过new生成包装对象。
二、场景
代码如下:
[java]view plaincopy
14 publicstaticvoid main(String[] args){
15 Scanner input = new Scanner(System.in);
16 while(input.hasNextInt()){
17 int ii = input.nextInt();
18 System.out.println("\n===" + ii + "的相等判断 ===");
19 //通过两个new产生的Integer对象
20 Integer i = new Integer(ii);
21 Integer j = new Integer(ii);
22 System.out.println("new 产生的对象:" + (i == j));
23
24 //基本类型转换为包装类型后比较
25 i = ii;
26 j = ii;
27 System.out.println("基本类型转换的对象:" + (i == j));
28
29 //通过静态方法生成的一个实例
30 i= Integer.valueOf(ii);
31 j = Integer.valueOf(ii);
32 System.out.println("valueOf产生的对象:" + (i == j));
33 }
34 }
分别输入127、128、55,结果如下:
===127的相等判断===
new产生的对象:false
基本类型转换的对象:true
valueOf产生的对象:true
===128的相等判断===
new产生的对象:false
基本类型转换的对象:false
valueOf产生的对象:false
===555的相等判断===
new产生的对象:false
基本类型转换的对象:false
valueOf产生的对象:false
通过上面的分析,-128--127是直接从整型池中获得的,不管你输入多少次127数字,获得的都是同一个对象。而128、555超出了整型范围,是通过new产生的新对象。
三、建议
声明包装类型的时候,使用valueOf()生成,而不是通过构造函数生成。这样使用整型池,不仅仅提高了系统性能,同时节约了内存空间。
转载于:https://blog.51cto.com/magina/1325396