java.util.Collections類的unmodifiableSortedMap()方法用於返回指定的已排序映射的不可修改視圖。此方法允許模塊為用戶提供對內部排序映射的隻讀訪問權限。對返回的排序圖“read through”到指定排序圖的查詢操作。嘗試通過其集合視圖或通過其subMap,headMap或tailMap視圖直接修改返回的已排序Map會導致UnsupportedOperationException。
如果指定的排序圖可序列化,則返回的排序圖將可序列化。
用法:
public static <K, V> SortedMap<K, V> unmodifiableSortedMap(SortedMap<K, ? extends V> m)
參數:此方法將已排序的映射作為參數,要為其返回不可修改的視圖。
返回值:此方法返回指定排序映射的不可修改視圖。
以下示例說明了unmodifiableSortedMap()方法
示例1:
// Java program to demonstrate
// unmodifiableSortedMap() method
// for <String, String> value
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// creating object of SortedMap<String, String>
SortedMap<String, String>
map = new TreeMap<String, String>();
// populate the map
map.put("First", "10");
map.put("Second", "20");
map.put("Third", "30");
// make the map unmodifiable
Map<String, String>
unmodsortmap = Collections
.unmodifiableSortedMap(map);
// printing unmodifiablemap
System.out.println("Initial sorted map value: "
+ map);
}
catch (UnsupportedOperationException e) {
System.out.println("Exception thrown : " + e);
}
}
}
輸出:
Initial sorted map value: {First=10, Second=20, Third=30}
示例2:對於UnsupportedOperationException
// Java program to demonstrate
// unmodifiableSortedMap() method
// For UnsupportedOperationException
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
// creating object of SortedMap<String, String>
SortedMap<String, String>
map = new TreeMap<String, String>();
// populate the map
map.put("First", "10");
map.put("Second", "20");
map.put("Third", "30");
// make the map unmodifiable
Map<String, String>
unmodsortmap = Collections
.unmodifiableSortedMap(map);
// printing unmodifiablemap
System.out.println("unmodifiableSortedMap value: "
+ map);
System.out.println("\nTrying to modify"
+ " the unmodifiable SortedMap");
unmodsortmap.put("Forth", "40");
}
catch (UnsupportedOperationException e) {
System.out.println("Exception thrown : " + e);
}
}
}
輸出:
unmodifiableSortedMap value: {First=10, Second=20, Third=30} Trying to modify the unmodifiable SortedMap Exception thrown : java.lang.UnsupportedOperationException
相關用法
- Java Collections max()用法及代碼示例
- Java Collections min()用法及代碼示例
- Java Collections list()用法及代碼示例
- Java Collections checkedSortedSet()用法及代碼示例
- Java Collections newSetFromMap()用法及代碼示例
- Java Collections fill()用法及代碼示例
- Java Collections enumeration()用法及代碼示例
- Java Collections copy()用法及代碼示例
- Java Collections singletonList()用法及代碼示例
- Java Collections replaceAll()用法及代碼示例
- Java Collections synchronizedSortedMap()用法及代碼示例
- Java Collections synchronizedSet()用法及代碼示例
- Java Collections synchronizedMap()用法及代碼示例
- Java Collections synchronizedSortedSet()用法及代碼示例
- Java Collections swap()用法及代碼示例
注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 Collections unmodifiableSortedMap() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。