Friday, 4 April 2014

Removes the element at the specified position

E remove(int index)
   Removes the element at the specified position in this list. Return the element previously at the specified position

import java.util.*;

class ListRemove{
 public static void main(String args[]){
  List<Integer> myList = new ArrayList<> ();
  
  /* Add Elements to myList */
  myList.add(10);
  myList.add(20);
  myList.add(30);
  myList.add(40);
  
  System.out.println("Elements in myList are");
  System.out.println(myList);
  
  for(int i=3; i >= 0; i--){
   System.out.println("Removing the Element " + myList.remove(i) + " at index " + i);
   System.out.println(myList);
  }
 } 
}

Output
Elements in myList are
[10, 20, 30, 40]
Removing the Element 40 at index 3
[10, 20, 30]
Removing the Element 30 at index 2
[10, 20]
Removing the Element 20 at index 1
[10]
Removing the Element 10 at index 0
[]

1. throws UnsupportedOperationException if the remove operation is not supported by this list
import java.util.*;

class ListRemoveUnsupport{
 public static void main(String args[]){
  List<Integer> myList = new ArrayList<> ();
  List<Integer> unmodifiable;
  
  /* Add Elements to myList */
  myList.add(10);
  myList.add(20);
  myList.add(30);
  myList.add(40);
  
  unmodifiable = Collections.unmodifiableList(myList);
  
  System.out.println("Elements in unmodifiable List are");
  System.out.println(unmodifiable);
  
  unmodifiable.remove(1);
 } 
}

Output

Elements in unmodifiable List are
[10, 20, 30, 40]
Exception in thread "main" java.lang.UnsupportedOperationException
        at java.util.Collections$UnmodifiableList.remove(Unknown Source)
        at ListRemoveUnsupport.main(ListRemoveUnsupport.java:19)

2. throws IndexOutOfBoundsException if the index is out of range

import java.util.*;

class ListRemoveIndexOut{
 public static void main(String args[]){
  List<Integer> myList = new ArrayList<> ();
  
  /* Add Elements to myList */
  myList.add(10);
  myList.add(20);
  myList.add(30);
  myList.add(40);
    
  System.out.println("Elements in myList are");
  System.out.println(myList);
  
  myList.remove(-1);
 } 
}

Output
Elements in myList are
[10, 20, 30, 40]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
        at java.util.ArrayList.elementData(Unknown Source)
        at java.util.ArrayList.remove(Unknown Source)
        at ListRemoveIndexOut.main(ListRemoveIndexOut.java:16)


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment