Yes, We can insert null values to a list easily using its add() method. In case of List implementation does not support null then it will throw NullPointerException.
boolean add(E e)
Appends the specified element to the end of this list.
E − The runtime type of the element.
e − The element to append to this list
Return true.
UnsupportedOperationException − If this list does not support the add operation
ClassCastException − If the specified element's class prevents it from being added to this list
NullPointerException − If the specified element is null and this list does not allow null elements
IllegalArgumentException − If some properties of this element prevent it from being added to this list
The following example demonstrates how to use the add() method to insert null values into a list.
package com.tutorialspoint; import java.util.ArrayList; import java.util.List; public class CollectionsDemo { public static void main(String[] args) { // Create a list object List<String> list = new ArrayList<>(); // add elements to the list list.add("A"); list.add(null); list.add("B"); list.add(null); list.add("C"); // print the list System.out.println(list); } }
This will produce the following result −
[A, null, B, null, C]
The above is the detailed content of Can we insert null value in Java list?. For more information, please follow other related articles on the PHP Chinese website!