Java Collections emptySortedSet()
Java Collections 类的
emptySortedSet()方法用于获取没有元素的排序Set。这些空集本质上是不可变的。
语法
以下是
emptySortedSet()方法的声明:
public static final <E> SortedSet<E> emptySortedSet()
参数
此方法不接受任何参数。
返回
emptySortedSet()方法返回一个空的已排序Set。
异常
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);
}
}
输出:
示例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)