当前位置: 代码迷 >> J2SE >> 关于ArrayList中装箱与拆箱的有关问题
  详细解决方案

关于ArrayList中装箱与拆箱的有关问题

热度:84   发布时间:2016-04-23 19:56:13.0
关于ArrayList中装箱与拆箱的问题
本帖最后由 szhielelp 于 2015-02-02 10:46:00 编辑
package javatest;

import java.util.ArrayList;

public class Main {
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<>();
al.add(1);
al.add(1);

System.out.println(al.get(0) == al.get(1));
System.out.println(new Integer(0) == new Integer(0));
}
}


为什么输出
true
false

我查看了一下get的源码


    public E get(int index) {
        rangeCheck(index);

        return elementData(index);
    }


    E elementData(int index) {
        return (E) elementData[index];
    }


这个E不是Integer嘛,他并没有转换成int类型
为什么会这样,这两种情况有什么区别
------解决思路----------------------
我来试着解释一下:
常量-127到+128,会自动装箱、拆箱。
每次装箱的时候,一个整数一直都对应一个封装类型对象,即:-127到+128会分别对应256个Integer对象。
当1需要装箱时,会找到1对应的Integer,第二次1再装箱时,还会找同一个对象。

效果应该等同如下:
     Integer i = new Integer(0);
        al.add(i);
        al.add(i);

所以当get的时候,返回的都是同一个地址的整型对象
  相关解决方案