Collections

Arraylist add() in Java Code With Examples

Table of Contents

Program

import java.util.ArrayList;
public class ArrayListAddSet 
{
   public static void main(String[] args) 
  {     
      ArrayList<Integer> ven = new ArrayList<Integer>(5);   
      ven.add(15);
      ven.add(20);
      ven.add(25); 
      System.out.println("array add = ");
      for (Integer number : ven) 
      {    
        System.out.println(number);
      }
      ven.add(2, 25);
      System.out.println("array after inserting = ");
      for (Integer number : ven) 
      {
         System.out.println(number);
      }
      ven.set(2,55); 
      System.out.println("array after setting:");
      for (Integer number : ven) 
      {
         System.out.println("Number = " + number);
      } 
  }
}

Output

array add =
15
20
25
array after inserting =
15
20
25
25
array after setting:
Number = 15
Number = 20
Number = 55
Number = 25 */ 

Description

public void add​(int index, E element)

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 (adds one to their indices).

Specified by:

add in interface List<E>

Overrides:

add in class AbstractList<E>

Parameters:

index – index at which the specified element is to be inserted
element – element to be inserted

Throws:

IndexOutOfBoundsException – if the index is out of range (index < 0 || index > size())

public boolean add​(E e)

Appends the specified element to the end of this list.

Specified by:

add in interface Collection<E>
add in interface List<E>

Overrides:

add in class AbstractList<E>

Parameters:

e – element to be appended to this list

Returns:

true (as specified by Collection.add(E))

public E set​(int index, E element)

Replaces the element at the specified position in this list with the specified element.

Specified by:

set in interface List<E>

Overrides:

set in class AbstractList<E>

Parameters:

index – index of the element to replace
element – element to be stored at the specified position

Returns:

the element previously at the specified position

Throws:

IndexOutOfBoundsException – if the index is out of range (index < 0 || index >= size())*/