Java ArrayList.add() Method

 Posted On  | Yashwant Chavan 

In this tutorial you will learn about Java ArrayList add() method. add method is used for adding an element to the ArrayList.

syntax

boolean java.util.ArrayList.add(E e)

Method appends the specified element to the end of this list. It return true if element added successfully

void java.util.ArrayList.add(int index, E element)

Method inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right.

parameters

index at which the specified element is to be inserted

element the element to be inserted.

exception

IndexOutOfBoundsException if the index is out of range.

Java ArrayList add Element Example

Refer below steps

  • Constructs an empty list with an initial capacity using new ArrayList<String>()
  • Appends the element to the end of this list using cities.add("Mumbai") method.
  • Here we have added element to specific index position using cities.add(2, "Delhi")
  • Print the elements of ArrayList using forloop.
package com.technicalkeeda.app;

import java.util.ArrayList;

public class ArrayListAddElement {
    public static void main(String[] args) {

        ArrayList <String> cities = new ArrayList <String> ();
        cities.add("Mumbai");
        cities.add("Pune");
        cities.add("Bengaluru");

        cities.add(2, "Delhi");

        for (String city: cities) {
            System.out.println("City:- " + city);
        }

    }
}

Output

City:- Mumbai
City:- Pune
City:- Delhi
City:- Bengaluru 


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0325 seconds.