TreeMap V put(K key,V value) Method Example Program


Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.

Program

package com.candidjava;

import java.util.TreeMap;

/**
 * @author: Hari Haran
 * @discription: The put(K key,V value) method is used to associate the
 *               specified value with the specified key in this map. If the map
 *               previously contained a mapping for the key, the old value is
 *               replaced.
 */

public class TreeMapPut {
	public static void main(String[] args) {
		TreeMap<Integer, String> tm = new TreeMap<Integer, String>();

		tm.put(1, "Anand");
		tm.put(2, "Hari Haran");
		tm.put(8, "Kamal");
		tm.put(4, "Karthikeyan");
		tm.put(5, "Mohan");
		tm.put(6, "Vinoth");
		tm.put(7, "Hari Haran");

		System.out.println("Value before modification: " + tm);
		System.out.println("Value returned: " + tm.put(3, "TP"));
		System.out.println("Value after modification: " + tm);
	}

}

Output

Value before modification: {1=Anand, 2=Hari Haran, 4=Karthikeyan, 5=Mohan, 6=Vinoth, 7=Hari Haran, 8=Kamal}
Value returned: null
Value after modification: {1=Anand, 2=Hari Haran, 3=TP, 4=Karthikeyan, 5=Mohan, 6=Vinoth, 7=Hari Haran, 8=Kamal}

Explanation

public V put(K key,V value)
Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.
Specified by:
put in interface Map<K,V>
Overrides:
put in class AbstractMap<K,V>
Parameters:
key - key with which the specified value is to be associated
value - value to be associated with the specified key
Returns:
the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key.)
Throws:
ClassCastException - if the specified key cannot be compared with the keys currently in the map
NullPointerException - if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys


Related Post

Comments


©candidjava.com