Friday, 4 April 2014

Insert Element At Particular position

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.

import java.util.*;
class ListAddAtIndex{
 public static void main(String args[]){
  List<Integer> myList = new LinkedList<> ();
  
  myList.add(6);
  myList.add(7);
  myList.add(8);
  myList.add(9);
  
  System.out.println("Elements in myList are");
  System.out.println(myList);
  
  for(int i=0; i < 6; i++){
   System.out.println("Adding " + i + " At " + i + "th index");
   myList.add(i, i);
   System.out.println(myList);
  }
 }
}

Output
Elements in myList are
[6, 7, 8, 9]
Adding 0 At 0th index
[0, 6, 7, 8, 9]
Adding 1 At 1th index
[0, 1, 6, 7, 8, 9]
Adding 2 At 2th index
[0, 1, 2, 6, 7, 8, 9]
Adding 3 At 3th index
[0, 1, 2, 3, 6, 7, 8, 9]
Adding 4 At 4th index
[0, 1, 2, 3, 4, 6, 7, 8, 9]
Adding 5 At 5th index
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

1. throws UnsupportedOperationException if the add operation is not supported by this list

import java.util.*;
class ListAddAtIndexUnsupport{
 public static void main(String args[]){
  List<Integer> myList = new LinkedList<> ();
  List<Integer> unmodifiable;
  
  myList.add(6);
  myList.add(7);
  myList.add(8);
  myList.add(9);
  
  System.out.println("Elements in myList are");
  System.out.println(myList);
  
  unmodifiable = Collections.unmodifiableList(myList);
  System.out.println("Trying to add Elements to unmodifiable list");
  unmodifiable.add(0, 123); 
 }
}

Output

Elements in myList are
[6, 7, 8, 9]
Trying to add Elements to unmodifiable list
Exception in thread "main" java.lang.UnsupportedOperationException
        at java.util.Collections$UnmodifiableList.add(Unknown Source)
        at ListAddAtIndexUnsupport.main(ListAddAtIndexUnsupport.java:17)

2. throws ClassCastException if the class of the specified element prevents it from being added to this list

3. throws NullPointerException if the specified element is null and this list does not permit null elements

4. throws IllegalArgumentException if some property of the specified
element prevents it from being added to this list

5. throws IndexOutOfBoundsException if the index is out of range





Prevoius                                                 Next                                                 Home

No comments:

Post a Comment