Tuesday 3 June 2014

HashMap : clear() : Removes all the mappings from this map

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

import java.util.*;

class HashMapClear{
  public static void main(String args[]){
  Map<Integer, String> myMap1 = new HashMap<> ();
  
  /* Add data to the myMap1 */
  myMap1.put(1, "First");
  myMap1.put(2, "Second");
  myMap1.put(3, "Third");
  myMap1.put(4, "Fourth");
  
  System.out.println("Data in myMap1 is");
  System.out.println(myMap1);
  
  System.out.println("\nCalling clear method on map");
  myMap1.clear();
  
  System.out.println("\nData in myMap1 is");
  System.out.println(myMap1);
  }
}


Output
Data in myMap1 is
{1=First, 2=Second, 3=Third, 4=Fourth}

Calling clear method on map

Data in myMap1 is
{}

1. Implement the clear functionality for the HashMap
import java.util.*;

class HashMapClearEx{

  static void clearMap(Map myMap1){
    Set<Integer> mySet = myMap1.keySet();
  
  int size = myMap1.size();
  Object keys[] = new Object[size];
  int i=0;
  
  Iterator iter1 = mySet.iterator();
  
  while(iter1.hasNext()){
    keys[i] = iter1.next();
  i++;
  }
  
  for(i=0; i < size; i++)
  myMap1.remove(keys[i]);
  }
  
  public static void main(String args[]){
  Map<Integer, String> myMap1 = new HashMap<> ();
  
  /* Add data to the myMap1 */
  myMap1.put(1, "First");
  myMap1.put(2, "Second");
  myMap1.put(3, "Third");
  myMap1.put(4, "Fourth");
  
  System.out.println("Data in myMap1 is");
  System.out.println(myMap1);
  
  System.out.println("\nCalling clear method on map");
  clearMap(myMap1);
  
  System.out.println("\nData in myMap1 is");
  System.out.println(myMap1);
  }
}

Output
Data in myMap1 is
{1=First, 2=Second, 3=Third, 4=Fourth}

Calling clear method on map

Data in myMap1 is
{}

Method “clearMap” gets all the keys of the given Map using iterator and removes each key, value mapping from the Map.

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment