Java教程

Java Collections unmodifiableSortedSet()

Java集合类的 unmodifiableSortedSet()方法用于获取不可修改的

语法

以下是 unmodifiableSortedSet()方法的声明:
public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s) 

参数

参数 说明 必需/可选
s 这是要返回其不可修改视图的排序集。 必需

返回

unmodifiableSortedSet()方法返回指定Sorted Set的不可修改视图。

异常

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)

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