Java 集合 emptySet() 方法



描述

Java 集合 emptySet() 方法用於獲取空集(不可變)。此集合是可序列化的。

宣告

以下是 java.util.Collections.emptySet() 方法的宣告。

public static final <T> Set<T> emptySet()

引數

返回值

異常

獲取整數的空集示例

以下示例演示瞭如何使用 Java 集合 emptySet() 方法獲取整數的空集。我們使用 emptySet() 方法建立了一個空集,然後嘗試向其中新增一些元素,這將導致異常。

 
package com.tutorialspoint;

import java.util.Collections;
import java.util.Set;

public class CollectionsDemo {
   public static void main(String args[]) {
      
      // create an empty set    
      Set<Integer> emptySet = Collections.emptySet();

      System.out.println("Created empty immutable set: "+emptySet);

      // try to add elements
      emptySet.add(1);
      emptySet.add(2);
   }    
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果。由於列表是不可變的,因此將丟擲異常。

Created empty immutable set: []
Exception in thread "main" java.lang.UnsupportedOperationException
	at java.base/java.util.AbstractCollection.add(AbstractCollection.java:267)
	at com.tutorialspoint.CollectionsDemo.main(CollectionsDemo.java:15)

獲取字串的空集示例

以下示例演示瞭如何使用 Java 集合 emptySet() 方法獲取字串的空集。我們使用 emptySet() 方法建立了一個空集,然後嘗試向其中新增一些元素,這將導致異常。

 
package com.tutorialspoint;

import java.util.Collections;
import java.util.Set;

public class CollectionsDemo {
   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 com.tutorialspoint.CollectionsDemo.main(CollectionsDemo.java:15)

獲取物件的空集示例

以下示例演示瞭如何使用 Java 集合 emptySet() 方法獲取 Student 物件的空集。我們使用 emptySet() 方法建立了一個空集,然後嘗試向其中新增一些元素,這將導致異常。

 
package com.tutorialspoint;

import java.util.Collections;
import java.util.Set;

public class CollectionsDemo {
   public static void main(String args[]) {
      
      // create an empty set    
      Set<Student> emptySet = Collections.emptySet();

      System.out.println("Created empty immutable set: "+emptySet);

      // try to add elements
      emptySet.add(new Student(1, "Julie"));
      emptySet.add(new Student(2, "Robert"));
   }    
}
class Student {
   int rollNo;
   String name;

   Student(int rollNo, String name){
      this.rollNo = rollNo;
      this.name = name;
   }

   @Override
   public String toString() {
      return "[ " + this.rollNo + ", " + this.name + " ]";
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果。由於列表是不可變的,因此將丟擲異常。

Created empty immutable set: []
Exception in thread "main" java.lang.UnsupportedOperationException
	at java.base/java.util.AbstractCollection.add(AbstractCollection.java:267)
	at com.tutorialspoint.CollectionsDemo.main(CollectionsDemo.java:15)
java_util_collections.htm
廣告