當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java Collections unmodifiableSortedSet()用法及代碼示例

Java Collections 類的 unmodifiableSortedSet() 方法用於獲取指定排序集的不可修改視圖。

用法

以下是 unmodifiableSortedSet() 方法的聲明:

public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s)

參數

參數 描述 必需/可選
s 它是要為其返回不可修改視圖的排序集。 Required

返回

unmodifiableSortedSet() 方法返回指定排序集的不可修改視圖。

異常

NA

例子1

import java.util.*;
public class CollectionsUnmodifiableSortedSetExample1 {
	public static void main(String[] args) {
	      SortedSet<String> set = new TreeSet<String>();
	      //Add values in the set
	      set.add("Facebook");
	      set.add("Twitter");
	      set.add("Whatsapp");
	      set.add("Instagram");
	      //Create a Unmodifiable sorted set
	      SortedSet<String> set2 = Collections.unmodifiableSortedSet(set);
	      System.out.println("Unmodifiable Sorted set is:"+set2);
	      set.add("Google");
	      System.out.println("Unmodifiable Sorted set after modify is:"+set2);
	      }
}

輸出:

Unmodifiable Sorted set is:[Facebook, Instagram, Twitter, Whatsapp]
Unmodifiable Sorted set after modify is:[Facebook, Google, Instagram, Twitter, Whatsapp]

例子2

import java.util.*;
public class CollectionsUnmodifiableSortedSetExample2 {
	public static void main(String[] args) {
		SortedSet<Integer> set = new TreeSet<>();
            Collections.addAll(set, 1, 9, 7);
            System.out.println("Original Set:" + set);
            SortedSet<Integer> set2 = Collections.unmodifiableSortedSet(set);
            System.out.println("Unmodifiable Sorted Set:" + set2);
            //Modifying the original Set
            set.add(10);
            System.out.println("Unmodifiable Sorted Set:" + set2);
	      }
}

輸出:

Original Set:[1, 7, 9]
Unmodifiable Sorted Set:[1, 7, 9]
Unmodifiable Sorted Set:[1, 7, 9, 10]

例子3

import java.util.*;
public class CollectionsUnmodifiableSortedSetExample3 {
	public static void main(String[] args) {
		SortedSet<Integer> set = new TreeSet<>();
            Collections.addAll(set, 1, 4, 7);
            System.out.println("Original Set:" + set);
            SortedSet<Integer> set2 = Collections.unmodifiableSortedSet(set);
            set2.add(10);
	      }
}

輸出:

Original Set:[1, 4, 7]
Exception in thread "main" java.lang.UnsupportedOperationException
	at java.base/java.util.Collections$UnmodifiableCollection.add(Collections.java:1056)
	at myPackage.CollectionsUnmodifiableSortedSetExample3.main(CollectionsUnmodifiableSortedSetExample3.java:9)






相關用法


注:本文由純淨天空篩選整理自 Java Collections unmodifiableSortedSet() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。