When Java collections throw a NullPointerException when using Collections.addAll ()

In what condition did the method Collections.addAll()choose NullPointerException? The official docs mention:

NullPointerException - if the specified collection contains a null element and this collection does not allow null elements or if the specified collection is null

How to make this "collection not allow 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]
+4
source share
3 answers

null, . , . , , null, .

ArrayList, null, addAll() null .

Collection, null, ArrayDeque. var1 :

Collection<String> var1 = new ArrayDeque<String>();

NullPointerException, addAll().

+1

Java NullPointerException Collections.addAll()

Collections.addAll :

NullPointerException - elements null, c null, c elements null

:

, " "

. (ArrayList) :

, , null.

( .)

, ( List / , ), , , null ( List , , , ).

+7

Collection.addAll(). .

, " " [?]

, , , . Collection (ArrayList, LinkedList, HashSet,...) null. , , , , , null, - TreeSet, Comparator, null s.

, , null s, - . NullPointerException, . , , , , null, , , , null, null . NullPointerException, ( , ) . , , Collection.

+1

Source: https://habr.com/ru/post/1623110/


All Articles