HashSet添加null报空指针异常。
public class TestSet {
public static void main(String[] args) {
Set<Integer> hashSet = new HashSet<Integer>();
hashSet.add();
hashSet.add();
hashSet.add();
hashSet.add(null); // will throw null pointer
hashSet.add();
hashSet.add();
hashSet.add();
hashSet.add();
hashSet.add();
hashSet.add();
hashSet.add();
hashSet.add();
hashSet.add();
Iterator<Integer> it = hashSet.iterator();
while(it.hasNext()){
int i = it.next();
System.out.print(i+" ");
}
}
}
Java集合类不能存储基本数据类型(如果要存储基本数据类型可以使用第三方API,如Torve),所以当执行如下代码:
hashSet.add();
hashSet.add();
实际上执行的是:
hashSet.add(new Integer());
hashSet.add(new Integer());
向HashSet中添加null值并不是产生空指针异常的原因,HashSet中是可以添加null值的。NPE是因为在遍历set时需要把值拆箱为基本数据类型:
while(it.hasNext()){
int i = it.next();
System.out.print(i+" ");
}
如果值为null,JVM试图把它拆箱为基本数据类型就会导致NPE。
装箱相当于执行
Integer.valueOf(100)
。
拆箱相当于执行
i.intValue()
。
此时相当于null调用intValue()方法,所以报NPE。
可以把代码修改为:
while(it.hasNext()){
final Integer i = it.next();
System.out.print(i+" ");
}
http://stackoverflow.com/questions/14774721/why-set-interface-does-not-allow-null-elements