关于 Iterator 的 remove 方法(太奇怪了,搞不懂)

来源:百度知道 编辑:UC知道 时间:2024/06/14 08:14:34
Collection c = new ArrayList();
int x = 128;
c.add("hello");
c.add((Integer)x);
System.out.println(c);
for (Iterator ii = c.iterator(); ii.hasNext();) {
if (ii.next()== (Integer)x) {
ii.remove();
}
}
System.out.println(c);

当 c.add((Integer)x) 或者我写成 c.add(x) ,只有 -128〈= x 〈= 127 的时候,才能remove掉。

其他值,程序没有remove掉。

我想知道为什么。

我看API :

保持 int 类型的最大值的常量可取的值为 2的31次方-1。
保持 int 类型的最小值的常量可取的值为 -2的31次方

望高手解答! 万分感谢
您误解我的意思了
就我写的程序
为什么小于-128或者大于128的数 就remove 不掉呢 ?

在JAVA类库的源码java/lang/Integer.java类中有这么一个内部类
private static class IntegerCache {
private IntegerCache(){}

static final Integer cache[] = new Integer[-(-128) + 127 + 1];

static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Integer(i - 128);
}
}

public static Integer valueOf(int i) {
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache
return IntegerCache.cache[i + offset];
}
return new Integer(i);
}
这段代码,因为你用的是5.0中的自动装箱特性.从理论上来说是Integer是一个类而int是基本数据类型.一个是对象而一个是数据类型两者是不能强制类型转换的,之所以你能用(Integer)x将int类型的变量x强制类型转换成Integer,创建出一个Integer类型的对象,是因为JAVA在5.0中当类Integer.class加载的时候就帮你自动在池中创建了-128到127之间的Integer对象.当你进行强制类型转换的时候并不是将创建出一个Integer对象出来而是去池中拿出一个-128到127之间的Integer对象来给你用。所以你知道为什么不能remove掉那个元素,因为池中没有所以虚拟机从池中拿不出来所以你强制类型转换以后就什么都没有了.
如果你要程序能remove掉X元素你可以这样写:
List c = new ArrayList();
int x = 128;
c.add(&q