当使用Collections.addAll()时,Java集合何时抛出NullPointerException异常 [英] When does Java Collections throw a NullPointerException while using Collections.addAll()
问题描述
Collections.addAll()
方法会在什么条件下抛出 NullPointerException
?官方文档提到:
NullPointerException - 如果指定的集合包含空元素,并且此集合不允许空元素, collection is null p>
public class CollectionImpl {
public void checkList(){
List< String> var1 = new ArrayList< String>();
var1.add(One);
var1.add(Two);
var1.add(Three);
System.out.println(var1:+ var1);
try {
if(Collections.addAll(var1,Four,Five,null,1)){
System.out.println );
}
}
catch(NullPointerException e){
System.out.println(Caught Null Pointer Exception+ e);
}
catch(IllegalArgumentException e){
System.out.println(Caught IllegalArgument Exception+ e);
}
finally {
System.out.println(var1:+ var1);
}
}
OUTPUT
var1:[1,2,null]
True
var1:[1,2, 5,null,6]
解决方案code> null 元素是集合实现本身的一个属性。它不是可以在集合的特定实例上更改的设置。正如其他人提到的,集合是否允许
null
应该总是记录在类的规范中。
ArrayList
允许null
元素,因此调用addAll()
null
的值将总是成功地将它们添加到列表中。
Collection
不允许null
值为ArrayDeque
。如果您按以下方式更改var1
的声明:Collection< String> ; var1 = new ArrayDeque< String>();
那么你会得到一个
NullPointerException
从调用addAll()
。Under what condition does the
Collections.addAll()
method throw aNullPointerException
? The official docs mention:NullPointerException - if the specified collection contains a null element and this collection does not permit null elements, or if the specified collection is null
How do I make sure that this "Collection does not permit null elements"
public class CollectionImpl { public void checkList(){ List<String> var1 = new ArrayList<String>(); var1.add("One"); var1.add("Two"); var1.add("Three"); System.out.println("var1 : " + var1); try{ if(Collections.addAll(var1,"Four" , "Five" , null , "1")){ System.out.println("True"); } } catch(NullPointerException e){ System.out.println("Caught Null Pointer Exception" + e); } catch(IllegalArgumentException e){ System.out.println("Caught IllegalArgument Exception" + e); } finally{ System.out.println("var1 : " + var1); } }
OUTPUT
var1 : [1, 2, null] True var1 : [1, 2, null, 4, 5, null, 6]
解决方案Whether a collection supports
null
elements is a property of the collection implementation itself. It's not a setting that can be changed on a particular instance of a collection. As others have mentioned, whether a collection permitsnull
should always be documented in the class's specification.Your example uses
ArrayList
, which permitsnull
elements, so callingaddAll()
withnull
values will always successfully add them to the list.An example of a
Collection
that doesn't permitnull
values isArrayDeque
. If you change your declaration ofvar1
as follows:Collection<String> var1 = new ArrayDeque<String>();
then you'll get a
NullPointerException
thrown from the call toaddAll()
.这篇关于当使用Collections.addAll()时,Java集合何时抛出NullPointerException异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!