Sunday, 13 April 2014

clear : Clear the Map

void clear()
Removes all of the mappings from this map.

import java.util.*;

class MapClear{
  public static void main(String args[]){
         Map<Integer, String> mapEx = new TreeMap<> ();
  
  /* Add Data to mapEx */
  mapEx.put(1, "HI");
  mapEx.put(2, "How");
  mapEx.put(3, "Are");
  
  System.out.println("Elements in mapEx are");
  System.out.println(mapEx);
  
  /* Clearing the Map data */
  mapEx.clear();
  
  System.out.println("\nElements in mapEx after clearing");
  System.out.println(mapEx);
  }
}

Output
Elements in mapEx are
{1=HI, 2=How, 3=Are}

Elements in mapEx after clearing
{}

1. throws UnsupportedOperationException if the clear operation is not supported by this map

import java.util.*;

class MapClearUnsupported{
  public static void main(String args[]){
         Map<Integer, String> mapEx = new TreeMap<> ();
  Map<Integer, String> unmodifiable;
  
  /* Add Data to mapEx */
  mapEx.put(1, "HI");
  mapEx.put(2, "How");
  mapEx.put(3, "Are");

  unmodifiable = Collections.unmodifiableMap(mapEx);
  
  System.out.println("Elements in unmodifiable are");
  System.out.println(unmodifiable);
  
  System.out.println("Clearning the Elements from unmodifiable map");
  unmodifiable.clear();
  }
}

Output
Elements in unmodifiable are
{1=HI, 2=How, 3=Are}
Clearning the Elements from unmodifiable map
Exception in thread "main" java.lang.UnsupportedOperationException
        at java.util.Collections$UnmodifiableMap.clear(Collections.java:1351)
        at MapClearUnsupported.main(MapClearUnsupported.java:19)

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment