當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java Collections emptySortedSet()用法及代碼示例

Java Collections 類的 emptySortedSet() 方法用於獲取沒有元素的有序 Set。這些空集本質上是不可變的。

用法

以下是 emptySortedSet() 方法的聲明:

public static final <E> SortedSet<E> emptySortedSet()

參數

此方法不接受任何參數。

返回

emptySortedSet() 方法返回一個空的有序集合。

異常

NA

兼容版本

Java 1.8 及以上

例子1

import java.util.*;
public class CollectionsEmptySortedSetExample1 {
    public static void main(String[] args) {		
         //Create an empty Sorted Set   
         SortedSet<String> EmptySet = Collections.<String>emptySortedSet();
         System.out.println("Empty Sorted Set:"+EmptySet);
         }	  
}

輸出:

Empty Sorted Set:[]

例子2

import java.util.*;
public class CollectionsEmptySortedSetExample2 {
    public static void main(String[] args) {		
        //Create an empty Sorted Set
          SortedSet<String> EmpSortSet = Collections.emptySortedSet();
          System.out.println("Created empty immutable Sorted Set:"+EmpSortSet);
          //Try to add elements
          EmpSortSet.add("A");
          EmpSortSet.add("B");
          }	  
}

輸出:

Created empty immutable Sorted Set:[]Exception in thread "main" 
java.lang.UnsupportedOperationException
	at java.base/java.util.Collections$UnmodifiableCollection.add(Collections.java:1056)
	at myPackage.CollectionsEmptySortedSetExample2.main(CollectionsEmptySortedSetExample2.java:9)

例子3

import java.util.*;
public class CollectionsEmptySortedSetExample3 {
    public static void main(String[] args) {		
        //Create an empty Sorted Set    
          SortedSet<Integer> empSortSet = Collections.emptySortedSet();
          empSortSet.add(1);
          empSortSet.add(2);    
          System.out.println("Created empty immutable Sorted Set:"+empSortSet);     
          }	  
}

輸出:

Exception in thread "main" java.lang.UnsupportedOperationException
	at java.base/java.util.Collections$UnmodifiableCollection.add(Collections.java:1056)
	at myPackage.CollectionsEmptySortedSetExample3.main(CollectionsEmptySortedSetExample3.java:8)





相關用法


注:本文由純淨天空篩選整理自 Java Collections emptySortedSet() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。