How do I add an element to an array list in Java?

JavaObject Oriented ProgrammingProgramming

Solution

We can add 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 add 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<Integer> list = new ArrayList<>();

      // add elements to the list
      list.add(1);
      list.add(2);
      list.add(3);
      list.add(4);
      list.add(5);
      list.add(6);

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

Output

This will produce the following result −

[1, 2, 3, 4, 5, 6]
raja
Updated on 09-May-2022 08:51:37

Advertisements