Java教程

Java Collections emptySet()

Java Collections 类的 emptySet()方法用于获取没有元素的Set。这些空集本质上是不可变的。

语法

以下是 emptySet()方法的声明:
public static final <T> Set<T> emptySet() 

参数

此方法不接受任何参数。

返回

emptySet()方法返回一个空的不可变Set。

异常

NA

兼容版本

Java 1.5及更高版本

示例1

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

示例2

import java.util.*;
public class CollectionsEmptySetExample2 {
    public static void main(String[] args) {      
        //Create an empty Set
          Set<String> EmptySet = Collections.emptySet();
          System.out.println("Created empty immutable Set: "+EmptySet);
          //try to add elements
          EmptySet.add("A");
          EmptySet.add("B");
          }   
}
输出:
Created empty immutable Set: []
Exception in thread "main" java.lang.UnsupportedOperationException
    at java.base/java.util.AbstractCollection.add(AbstractCollection.java:267)
    at myPackage.CollectionsEmptySetExample2.main(CollectionsEmptySetExample2.java:10)

示例3

import java.util.*;
public class CollectionsEmptySetExample3 {
    public static void main(String[] args) {      
        //Create an empty Set    
          Set<Integer> empSet = Collections.emptySet();
          empSet.add(1);
          empSet.add(2);    
          System.out.println("Created empty immutable Set: "+empSet);         
          }   
}
输出:
Exception in thread "main" java.lang.UnsupportedOperationException
    at java.base/java.util.AbstractCollection.add(AbstractCollection.java:267)
    at myPackage.CollectionsEmptySetExample3.main(CollectionsEmptySetExample3.java:8)

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