Sunday 8 June 2014

TreeMap : put(K key, V value) : Insert mapping to TreeMap

public V put(K key, V value)
Associates the specified value with the specified key in this map. Return the previous value associated with key, or null if there was no mapping for key.

import java.util.*;

class TreeMapPut{
 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);
 }
}

Output
Elements in myMap are
{2=w, 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

import java.util.*;

class TreeMapPutNullPointer{
 public static void main(String args[]){
  TreeMap<Integer, String> myMap;
  
  myMap = new TreeMap<> ();
  
  /* Add Elements to myMap */
  myMap.put(null, "w");

 }
}

Output
Exception in thread "main" java.lang.NullPointerException
        at java.util.TreeMap.compare(TreeMap.java:1290)
        at java.util.TreeMap.put(TreeMap.java:538)
        at TreeMapPutNullPointer.main(TreeMapPutNullPointer.java:10)

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