-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathUnmodifiableCollection.java
More file actions
40 lines (32 loc) · 999 Bytes
/
UnmodifiableCollection.java
File metadata and controls
40 lines (32 loc) · 999 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.di1shuai.java9.collection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author Shea
* @date 2021-01-21
* @description 不可变集合
*/
public class UnmodifiableCollection {
public static void main(String[] args) {
// before 9
List<String> stringList = new ArrayList<>();
stringList.add("Hello ");
stringList.add("Java 9");
List<String> unmodifiableList = Collections.unmodifiableList(stringList);
// after 9
List<String> unmodifiableList_9 = List.of("Hello ","Java 9");
try {
unmodifiableList.add("hi");
}catch (UnsupportedOperationException e){
System.err.println("无法添加");
e.printStackTrace();
}
try {
unmodifiableList_9.add("hi");
}catch (UnsupportedOperationException e){
System.err.println("无法添加");
e.printStackTrace();
}
}
}