Home > Java > javaTutorial > Can we insert null value in Java list?

Can we insert null value in Java list?

PHPz
Release: 2023-08-20 19:01:15
forward
1345 people have browsed it

Can we insert null value in Java list?

Solution

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.

Syntax

boolean add(E e)
Copy after login

Appends the specified element to the end of this list.

Type parameter

  • E − The runtime type of the element.

Parameters

  • e − The element to append to this list

Return value

Return true.

Throws

  • 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

Example

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);
   }
}
Copy after login

Output

This will produce the following result −

[A, null, B, null, C]
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template