Java Collections unmodifiableSortedMap()
unmodifiableSortedMap() 用于获取指定的SortedMap的不可修改视图。
1 语法
public static <K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap<K,? extends V> m)
2 参数
m:它是SortedMap,将为其返回不可修改的视图。
3 返回值
返回指定的SortedMap的不可修改视图。
4 unmodifiableSortedMap()示例1
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java Collections.unmodifiableSortedMap的例子
*/
import java.util.*;
public class Demo {
public static void main(String[] args) {
SortedMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
map.put(1, 1001);
map.put(4, 1004);
map.put(2, 1002);
map.put(3, 1003);
System.out.println("Original Map: " + map);
SortedMap<Integer, Integer> map2 = Collections.unmodifiableSortedMap(map);
map.put(5, 1005);
System.out.println("Unmodifiable Sorted Map: " + map2);
}
}
输出结果为:
Original Map: {1=1001, 2=1002, 3=1003, 4=1004}
Unmodifiable Sorted Map: {1=1001, 2=1002, 3=1003, 4=1004, 5=1005}
5 unmodifiableSortedMap()示例2
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java Collections.unmodifiableSortedMap的例子
*/
import java.util.*;
public class Demo {
public static void main(String[] args) {
SortedMap<String, String> map = new TreeMap<String, String>();
map.put("1", "Whatsapp");
map.put("4", "Instagram");
map.put("3", "Facebook");
map.put("2", "Twitter");
System.out.println("Original Map: " + map);
SortedMap<String, String> map2 = Collections.unmodifiableSortedMap(map);
map.put("5","Hangout");
System.out.println("Unmodifiable Sorted Map: " + map2);
}
}
输出结果为:
Original Map: {1=Whatsapp, 2=Twitter, 3=Facebook, 4=Instagram}
Unmodifiable Sorted Map: {1=Whatsapp, 2=Twitter, 3=Facebook, 4=Instagram, 5=Hangout}
6 unmodifiableSortedMap()示例3
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java Collections.unmodifiableSortedMap的例子
*/
import java.util.*;
public class Demo {
public static void main(String[] args) {
SortedMap<Integer, String> map = new TreeMap<>();
map.put(1, "one");
map.put(2, "two");
System.out.println("Original Map: " + map);
SortedMap<Integer, String> map2 = Collections.unmodifiableSortedMap(map);
map2.remove(1);
}
}
输出结果为:
Original Map: {1=one, 2=two}
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableMap.remove(Collections.java:1460)
at com.yiidian.Demo.main(Demo.java:19)
热门文章
优秀文章