Tuesday, 1 April 2014

Clear() : Removes all of the elements from this list

clear()
    Removes all of the elements from this list

import java.util.*;
class ListClear{
 public static void main(String args[]){
  List<Integer> myList = new ArrayList<> ();

  /* Add Elements to myList */
  for(int i=0; i < 10; i++){
   myList.add(i);
  }

  System.out.println("Elements in myList are ");
  System.out.println(myList +"\n");
  
  myList.clear();

  System.out.println("Elements in myList After calling clear");
  System.out.println(myList +"\n");
 }
}

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

Elements in myList After calling clear
[]

1. throws UnsupportedOperationException if the clear operation is not supported by this list.
import java.util.*;
class ListClearUnsupported{
 public static void main(String args[]){
  List<Integer> myList = new ArrayList<> ();
  List<Integer> unmodifiable;
  
  /* Add Elements to myList */
  for(int i=0; i < 10; i++){
   myList.add(i);
  }

  unmodifiable = Collections.unmodifiableList(myList);
  
  System.out.println("Elements in unmodifiable List are ");
  System.out.println(unmodifiable +"\n");
  
  unmodifiable.clear();

  System.out.println("Elements in unmodifiable List After calling clear");
  System.out.println(unmodifiable +"\n");
 }
}

Output
Elements in unmodifiable List are
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Exception in thread "main" java.lang.UnsupportedOperationException
        at java.util.Collections$UnmodifiableCollection.clear(Unknown Source)
        at ListClearUnsupported.main(ListClearUnsupported.java:17)



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment