当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


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)





相关用法


注:本文由纯净天空筛选整理自 Java Collections emptySet() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。