Java 集合 unmodifiableSet() 方法



描述

Java Collections unmodifiableSet() 方法返回指定集合的不可修改檢視。

宣告

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

public static <T> boolean addAll(Collection<? super T> c, T.. a)

引數

s - 這是要返回不可修改檢視的集合。

返回值

方法呼叫返回指定集合的不可修改檢視。

異常

從可變整數集合獲取不可變集合示例

以下示例演示了 Java Collection unmodifiableSet(Set) 方法的使用。我們建立了一個 Integer 型別的 Set 物件。添加了一些條目,然後使用 unmodifiableSet(Set) 方法,我們獲取了集合的不可變版本並列印了集合。

package com.tutorialspoint;

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

public class CollectionsDemo {
   public static void main(String[] args) {
      
      // create set
      Set<Integer> set = new HashSet<Integer>();

      // populate the set
      set.add(1); 
      set.add(2);
      set.add(3);

      // create a immutable set
      Set<Integer> immutableSet = Collections.unmodifiableSet(set);

      System.out.println("Immutable set is :"+immutableSet);
   }
}

輸出

讓我們編譯並執行以上程式,這將產生以下結果。

Immutable set is :[1, 2, 3]

從可變字串集合獲取不可變集合示例

以下示例演示了 Java Collection unmodifiableSet(Set) 方法的使用。我們建立了一個 String 型別的 Set 物件。添加了一些條目,然後使用 unmodifiableSet(Set) 方法,我們獲取了 map 的不可變版本並列印了 map。

package com.tutorialspoint;

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

public class CollectionsDemo {
   public static void main(String[] args) {
      
      // create set
      Set<String> set = new HashSet<String>();

      // populate the set
      set.add("TP"); 
      set.add("IS");
      set.add("BEST");

      // create a immutable set
      Set<String> immutableSet = Collections.unmodifiableSet(set);

      System.out.println("Immutable set is :"+immutableSet);
   }
}

輸出

讓我們編譯並執行以上程式,這將產生以下結果。

Immutable set is :[IS, BEST, TP]

從可變物件集合獲取不可變集合示例

以下示例演示了 Java Collection unmodifiableSet(Set) 方法的使用。我們建立了一個 String 和 Student 物件型別的 Set 物件。添加了一些條目,然後使用 unmodifiableSet(Set) 方法,我們獲取了 map 的不可變版本並列印了 map。

package com.tutorialspoint;

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

public class CollectionsDemo {
   public static void main(String[] args) {
      
      // create set
      Set<Student> set = new HashSet<Student>();

      // populate the set
      set.add(new Student(1, "Julie")); 
      set.add(new Student(2, "Robert"));
      set.add(new Student(3, "Adam"));

      // create a immutable set
      Set<Student> immutableSet = Collections.unmodifiableSet(set);

      System.out.println("Immutable set is :"+immutableSet);
   }
}
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 + " ]";
   }
}

輸出

讓我們編譯並執行以上程式,這將產生以下結果。

Immutable set is :[[ 1, Julie ], [ 2, Robert ], [ 3, Adam ]]
java_util_collections.htm
廣告