Friday, 30 May 2014

add (int index, E element) : Insert element at Particular index

public void add(int index, E element)
Inserts the specified element at the specified position in this list. Shifts the current and subsequent elements to right.

import java.util.*;

class ArrayListAddAtIndex{
 public static void main(String args[]){
  ArrayList<Integer> myList;
  myList = new ArrayList<> ();
  
  for(int i=0; i<5; i++){
   myList.add(i);
  }
  System.out.println("Elements in myList are");
  System.out.println(myList);
  
  System.out.println("\nAdding 10 at index 3");
  myList.add(3, 10);
  
  System.out.println("\nElements in myList are");
  System.out.println(myList);
 }
}

Output
Elements in myList are
[0, 1, 2, 3, 4]

Adding 10 at index 3

Elements in myList are
[0, 1, 2, 10, 3, 4]

1. Throws IndexOutOfBoundsException if index out f range.
import java.util.*;

class ArrayListAddAtIndexOut{
 public static void main(String args[]){
  ArrayList<Integer> myList;
  myList = new ArrayList<> ();
  
  for(int i=0; i<5; i++){
   myList.add(i);
  }
  System.out.println("Elements in myList are");
  System.out.println(myList);
  
  System.out.println("\nAdding 10 at index 10");
  myList.add(10, 10);
  
  System.out.println("\nElements in myList are");
  System.out.println(myList);
 }
}

Output
Elements in myList are
[0, 1, 2, 3, 4]

Adding 10 at index 10
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 10, Size:5
        at java.util.ArrayList.rangeCheckForAdd(ArrayList.java:612)
        at java.util.ArrayList.add(ArrayList.java:426)
        at ArrayListAddAtIndexOut.main(ArrayListAddAtIndexOut.java:15)

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment