-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathUnmodifiableListTest.java
More file actions
58 lines (54 loc) · 1.73 KB
/
UnmodifiableListTest.java
File metadata and controls
58 lines (54 loc) · 1.73 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
public class UnmodifiableListTest {
private static void printPersons(List<Person> persons) {
for (Person p : persons) {
System.out.print(p.name() + ", ");
}
System.out.println("");
}
public static void main(String[] args) {
List<Person> persons = new ArrayList<Person>();
persons.add(new Person("Yalun", 25));
persons.add(new Person("Jack", 30));
persons.add(new Person("Lucy", 16));
List<Person> unmodifiablePersons = Collections.unmodifiableList(persons);
System.out.println("Original: ");
printPersons(unmodifiablePersons);
// Try changing the collection through the view
try {
//unmodifiablePersons.add(new Person("Tim", 44));
unmodifiablePersons.remove(0);
} catch (UnsupportedOperationException e) {
System.out.println("UnsupportedOperationException!");
}
System.out.println("Now the array content is still:");
printPersons(unmodifiablePersons);
// Make a change to one element throught the view
try {
for (Person p : unmodifiablePersons) {
if (p.name().equals("Lucy")) {
p.setName("Jane");
}
}
} catch (Exception e) {
System.out.println("Exception!");
}
System.out.println("After making changes of an element through the view:");
printPersons(unmodifiablePersons);
System.out.println("Original list now is: ");
printPersons(persons);
// Remove the first element in the original array
try {
persons.remove(0);
persons.add(new Person("Tim", 44));
} catch (Exception e) {
System.out.println("Exception!");
}
System.out.println("After changing the original array: ");
printPersons(persons);
System.out.println("Through the view:");
printPersons(unmodifiablePersons);
}
}