java.util.TreeMap.remove() 方法
描述
remove(Object key) 方法用于从该 TreeMap 中删除此键的映射(如果存在)。
声明
以下是 java.util.TreeMap.remove() 方法的声明。
public V remove(Object key)
参数
key − 这是应该删除映射的键。
返回值
该方法调用返回与 key 关联的先前值,如果没有 key 映射,则返回 null。
异常
ClassCastException − 如果指定的键无法与映射中当前的键进行比较,则会引发此异常。
NullPointerException − 如果指定的键为空并且此映射使用自然排序,或者其比较器不允许空键,则会引发此异常。
示例
下面的例子展示了 java.util.TreeMap.remove() 的用法。
package com.tutorialspoint;
import java.util.*;
public class TreeMapDemo {
public static void main(String[] args) {
// creating tree map
TreeMap<Integer, String> treemap = new TreeMap<Integer, String>();
// populating tree map
treemap.put(2, "two");
treemap.put(1, "one");
treemap.put(3, "three");
treemap.put(6, "six");
treemap.put(5, "five");
System.out.println("Value before modification: "+ treemap);
// removing value at key 5
System.out.println("Removed value: "+treemap.remove(5));
System.out.println("Value after modification: "+ treemap);
}
}
让我们编译并运行上面的程序,这将产生以下结果.
Value before modification: {1=one, 2=two, 3=three, 5=five, 6=six}
Removed value: five
Value after modification: {1=one, 2=two, 3=three, 6=six}

