请教大神们一个java包装类的问题,
String str = "abc";
String str2 = "abc";
System.out.println(str == str2);
Integer i = Integer.valueOf(1);
Integer i2 = Integer.valueOf(1);
System.out.println(i ==i2);
我知道str和str2是存放在字符串常量池中的,所以他们是相等的,但是i和i2相等能说明这两个是同一个对象吗? 我认为i和i2相等是因为 比较它们的时候自动拆箱,按照基本数据类型来比较了, 另外关于基本类型比如int,也是类似于String常量池那样存储的吗? 就是说我有两个int值如果相等的话,它们在内存中是否就是相同的呢?
这个问题是在看 think in java 第17章 深入理解容器 时想到的,书中在将填充容器时写了一个填充Integer的自定义的List,然后说这是享元,我有点想不明白,求大神们指点呀!下面是书中的代码:
public class CountingIntegerList
extends AbstractList<Integer> {
private int size;
public CountingIntegerList(int size) {
this.size = size < 0 ? 0 : size;
}
public Integer get(int index) {
//我这里不太明白,难道每次按照相同index取出的Integer都是同一个对象???
return Integer.valueOf(index);
}
public int size() { return size; }
public static void main(String[] args) {
System.out.println(new CountingIntegerList(30));
}
}