Java Collections unmodifiableSet()
unmodifiableSet() 用于获取指定集合的不可修改视图。
1 语法
public static <T> Set<T> unmodifiableSet(Set<? extends T> s)
2 参数
s:这是要返回不可修改视图的集合。
3 返回值
返回指定集合的不可修改视图。
4 unmodifiableSet()示例1
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java Collections.unmodifiableSet的例子
*/
import java.util.*;
public class Demo {
public static void main(String[] args) {
Set<Integer> set = new TreeSet<>();
Collections.addAll(set, 1,2,3,4,5);
System.out.println("Initial Set: " + set);
Set<Integer> set2 = Collections.unmodifiableSet(set);
System.out.println("Unmodifiable Set: " + set2);
//Modifying the original set
set.add(15);
System.out.println("Unmodifiable Set: " + set2);
}
}
输出结果为:
Initial Set: [1, 2, 3, 4, 5]
Unmodifiable Set: [1, 2, 3, 4, 5]
Unmodifiable Set: [1, 2, 3, 4, 5, 15]
5 unmodifiableSet()示例2
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java Collections.unmodifiableSet的例子
*/
import java.util.*;
public class Demo {
public static void main(String[] args) {
Set<String> set = new TreeSet<>();
Collections.addAll(set, "Google", "Facebook", "Instagram");
System.out.println("Initial Set: " + set);
Set<String> set2 = Collections.unmodifiableSet(set);
System.out.println("Unmodifiable Set: " + set2);
//Modifying the original set
set.add("Twitter");
System.out.println("Unmodifiable Set: " + set2);
}
}
输出结果为:
Initial Set: [Facebook, Google, Instagram]
Unmodifiable Set: [Facebook, Google, Instagram]
Unmodifiable Set: [Facebook, Google, Instagram, Twitter]
6 unmodifiableSet()示例3
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java Collections.unmodifiableSet的例子
*/
import java.util.*;
public class Demo {
public static void main(String[] args) {
Set<Integer> set = new TreeSet<>();
Collections.addAll(set, 11, 13, 17);
System.out.println("Original Set: " + set);
Set<Integer> set2 = Collections.unmodifiableSet(set);
set2.add(19);
}
}
输出结果为:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add(Collections.java:1055)
at com.yiidian.Demo.main(Demo.java:18)
Original Set: [11, 13, 17]
热门文章
优秀文章