Java SortedMap remove()方法及示例

来源:这里教程网 时间:2026-02-17 21:11:25 作者:

Java SortedMap remove()方法及示例

Java中SortedMap接口的 remove() 方法用于从该地图中删除某个键的映射,如果该键存在于该地图中。

语法

V remove(Object key)

参数: 该方法有唯一的参数 key ,其映射要从地图中删除。

返回: 该方法返回该 SortedMap 先前关联键的值,如果该SortedMap不包含该键的映射,则返回空。

注意 :SortedMap中的remove()方法是继承自Java中的Map接口。

下面的程序说明了remove()方法的实现。

程序1 :

// Java code to show the implementation of// remove method in SortedMap interface import java.util.*; public class GfG {     // Driver code    public static void main(String[] args)    {         // Initializing a SortedMap        SortedMap<Integer, String> map            = new TreeMap<>();        map.put(1, "One");        map.put(3, "Three");        map.put(5, "Five");        map.put(7, "Seven");        map.put(9, "Nine");        System.out.println(map);         map.remove(3);         System.out.println(map);         // If it doesn't exists, returns        // null and does not affects the map        map.remove(2);         System.out.println(map);    }}

输出

{1=One, 3=Three, 5=Five, 7=Seven, 9=Nine}{1=One, 5=Five, 7=Seven, 9=Nine}{1=One, 5=Five, 7=Seven, 9=Nine}

程序2: 下面的代码显示了remove()的实现。

// Java code to show the implementation of// remove method in SortedMap interface import java.util.*; public class GfG {     // Driver code    public static void main(String[] args)    {         // Initializing a SortedMap        SortedMap<String, String> map            = new TreeMap<>();         map.put("1", "One");        map.put("3", "Three");        map.put("5", "Five");        map.put("7", "Seven");        map.put("9", "Nine");        System.out.println(map);         map.remove("3");         System.out.println(map);    }}

输出

{1=One, 3=Three, 5=Five, 7=Seven, 9=Nine}{1=One, 5=Five, 7=Seven, 9=Nine}

**参考资料: ** https://docs.oracle.com/javase/7/docs/api/java/util/Map.html#put(K, %20V)

相关推荐