Sunday, 11 May 2014

LinkedList : add(int index, E element) : Add 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 LinkedListAddAtIndex{
 public static void main(String args[]){
  LinkedList<Integer> myList;
  myList = new LinkedList<> ();
  
  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 of range.
import java.util.*;

class LinkedListAddAtIndexOut{
 public static void main(String args[]){
  LinkedList<Integer> myList;
  myList = new LinkedList<> ();
  
  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);
 }
}

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.LinkedList.checkPositionIndex(LinkedList.java:558)
        at java.util.LinkedList.add(LinkedList.java:505)
        at LinkedListAddAtIndexOut.main(LinkedListAddAtIndexOut.java:15)



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment