Sunday 8 June 2014

TreeMap : remove (Object key) : Remove mapping

public V remove(Object key)
Removes the mapping for this key from this TreeMap if present. Return the previous value associated with key, or null if there was no mapping for key.

import java.util.*;

class TreeMapRemove{
 public static void main(String args[]){
  TreeMap<Integer, String> myMap;
  
  myMap = new TreeMap<> ();
  
  /* Add Elements to myMap */
  myMap.put(2, "w");
  myMap.put(4, "wx");
  myMap.put(6, "wxy");
  myMap.put(8, "wxyz");
  
  System.out.println("Elements in myMap are");
  System.out.println(myMap);
  
  System.out.println("Removing 2 from myMap");
  myMap.remove(2);
  
  System.out.println("Elements in myMap are");
  System.out.println(myMap);
 }
}

Output
Elements in myMap are
{2=w, 4=wx, 6=wxy, 8=wxyz}
Removing 2 from myMap
Elements in myMap are
{4=wx, 6=wxy, 8=wxyz}

1. Throws NullPointerException if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys.

2. Throws ClassCastException if the specified key cannot be compared with the keys currently in the map


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment