HashSet出现空指针异常(NullPointerException)
作者:互联网
HashSet可以存储null作为值,但是这样在增强for循环里遍历的时候会出现Exception in thread "main" java.lang.NullPointerException
错误。
package com.hbq.bugs;
import java.util.HashSet;
public class HashSetNullPoint {
public static void main(String[] args) {
HashSet<Integer> hs=new HashSet<>();
hs.add(74);
hs.add(null);
hs.add(89);
for (int i:hs) {//出现Exception in thread "main" java.lang.NullPointerException
System.out.println(i);
}
}
}
所以对于集合最好用迭代器去遍历。具体做法为:
package com.hbq.bugs;
import java.util.HashSet;
import java.util.Iterator;
public class HashSetNullPoint {
public static void main(String[] args) {
HashSet<Integer> hs = new HashSet<>();
hs.add(74);
hs.add(null);
hs.add(89);
for (Iterator iter = hs.iterator(); iter.hasNext(); ) {
System.out.println(iter.next());
}
}
}
标签:java,HashSet,hs,public,add,main,NullPointerException,指针 来源: https://blog.csdn.net/Doraemon_Nobita/article/details/115426263