TreeMap V remove(Object key) Method Example Program


Removes the mapping for this key from this TreeMap if present.

Program

package com.candidjava;

import java.util.TreeMap;

/**
 * @author: Hari Haran
 * @discription: The remove(Object key) method is used to remove the mapping for
 *               this key from this TreeMap if present.
 */

public class TreeMapRemove {
	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("Removed value: " + tm.remove(7));

		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}
Removed value: Hari Haran
Value after modification: {1=Anand, 2=Hari Haran, 4=Karthikeyan, 5=Mohan, 6=Vinoth, 8=Kamal}

Explanation

public V remove(Object key)
Removes the mapping for this key from this TreeMap if present.
Specified by:
remove in interface Map<K,V>
Overrides:
remove in class AbstractMap<K,V>
Parameters:
key - key for which mapping should be removed
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