Home » Java programming language

Java ArrayList add() Method with Example

ArrayList Class add() method: Here, we are going to learn about the add() method of ArrayList Class with its syntax and example.
Submitted by Preeti Jain, on January 18, 2020

ArrayList Class add() method

Syntax:

    public boolean add(T ele);
    public void add(int indices, T ele);
  • add() method is available in java.util package.
  • add(T ele) method is used to add the given ele(element) to the last of this Arraylist.
  • add(int indices, T ele) method is used to add the given ele(element) at the given indices in this Arraylist & shift other elements to the right side.
  • add(T ele) method does not throw an exception at the time of adding an element.
  • add(int indices, T ele) method may throw an exception at the time of adding an element at the given position.
    IndexOutOfBoundsException: This exception may throw when the given parameter indices are not in a range.
  • These are non-static methods, so it is accessible with class objects & if we try to access these methods with the class name then we will get an error.

Parameter(s):

  • In the first case, add(T ele)
    • T ele – represents the element to be added in this Arraylist.
  • In the second case, add(int indices, T ele)
    • int indices – represents the position of inserting the given element.
    • T ele – represents the element to be added in this Arraylist.

Return value:

In the first case, the return type of the method is boolean, it returns true if the given element is added successfully.

In the second case, the return type of the method is void, it does not return anything.

Example:

// Java program to demonstrate the example 
// of add() method of ArrayList.

import java.util.*;

public class AddOfArrayList {
    public static void main(String[] args) {
        // Create an ArrayList with initial 
        // capacity of storing elements

        ArrayList < String > arr_l = new ArrayList < String > (10);

        // By using add() method is to add 
        // elements in this ArrayList
        arr_l.add("C");
        arr_l.add("C++");
        arr_l.add("JAVA");
        arr_l.add("DOTNET");
        arr_l.add("PHP");

        // Display ArrayList 
        System.out.println("arr_l.add(obj) :" + arr_l);

        // By using add(int,T) method is to add the
        // elements at the given index in this ArrayList

        arr_l.add(2, "JSP");

        // Display ArrayList 
        System.out.println("arr_l.add(int,obj) : " + arr_l);
    }
}

Output

arr_l.add(obj) :[C, C++, JAVA, DOTNET, PHP]
arr_l.add(int,obj) : [C, C++, JSP, JAVA, DOTNET, PHP]


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.