How do I insert elements in a Java list?



Solution

We can insert element to an array list easily using its add() method.

Syntax

boolean add(E e)

Appends the specified element to the end of this list.

Type Parameter

  • − The runtime type of the element to be added.

Parameters

  • − Element to be appended to this list

Returns

It returns true.

Throws

  • UnsupportedOperationException − If the add operation is not supported by this list

  • ClassCastException − If the class of the specified element prevents it from being added to this list.

  • NullPointerException − If the specified element is null and this list does not permit null elements.

  • IllegalArgumentException − If some property of this element prevents it from being added to this list.

Example

The following example shows how to insert elements to the list using add() method.

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("B");
      list.add("C");

      // print the list
      System.out.println(list);
   }
}

Output

This will produce the following result −

[A, B, C]

Advertisements