Java教程

Java Collections emptySortedMap()

Java集合类的 emptySortedMap()方法返回一个不可变的空排序映射。

语法

以下是 emptySortedMap()方法的声明:
public static final <K,V> SortedMap<K,V> emptySortedMap()

参数

此方法不接受任何参数。

返回

emptySortedMap()方法返回一个空的不可变的已排序映射。

异常

NA

兼容版本

Java 1.8及更高版本

示例1

import java.util.*;
public class CollectionsEmptySortedMapExample1 {
    public static void main(String[] args) {      
         SortedMap<String,String> EmpSortedMap = Collections.emptySortedMap</span>();
         System.out.println("Created Empty Sorted Map: "+EmpSortedMap);
         }    
}
输出:
Created Empty Sorted Map: {}

示例2

import java.util.*;
public class CollectionsEmptySortedMapExample2 {
    public static void main(String[] args) {      
         SortedMap<String,String> EmpSortedMap = Collections.emptySortedMap</span>();
         System.out.println("Created Empty Sorted Map: "+EmpSortedMap);
         // try to add elements
         EmpSortedMap.put("1","from lidihuo.com");
         }    
}
输出:
Created Empty Sorted Map: {}
Exception in thread "main" java.lang.UnsupportedOperationException
    at java.base/java.util.Collections$UnmodifiableMap.put(Collections.java:1453)
    at myPackage.CollectionsEmptySortedMapExample2.main(CollectionsEmptySortedMapExample2.java:9)

示例3

import java.util.*;
public class CollectionsEmptySortedMapExample3 {
    public static void main(String[] args) {      
        //Create an empty Map  
          SortedMap<Integer, Integer> empSortedMap = Collections.emptySortedMap</span>();
          empSortedMap.put(1, 23424);
          empSortedMap.put(2, 65776);    
          System.out.println("Created empty immutable Sorted Map: "+empSortedMap);        
          }   
}
输出:
Exception in thread "main" java.lang.UnsupportedOperationException
    at java.base/java.util.Collections$UnmodifiableMap.put(Collections.java:1453)
    at myPackage.CollectionsEmptySortedMapExample3.main(CollectionsEmptySortedMapExample3.java:8)

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4