-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImmutableExample.java
More file actions
54 lines (50 loc) ยท 2.03 KB
/
ImmutableExample.java
File metadata and controls
54 lines (50 loc) ยท 2.03 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
package ch15.sec08;
import java.util.*;
public class ImmutableExample {
public static void main(String[] args) {
// List ๋ถ๋ณ ์ปฌ๋ ์
์์ฑ
List<String> immutable1 = List.of("A", "B", "C");
// immutable1.add("D"); (X)
// Set ๋ถ๋ณ ์ปฌ๋ ์
์์ฑ
System.out.println("immutable1 = " + immutable1);
Set<String> immutable2 = Set.of("A", "B", "C");
// immutable2.add("D"); (X)
System.out.println("immutable2 = " + immutable2);
// Map ๋ถ๋ณ ์ปฌ๋ ์
์์ฑ
Map<Integer, String> immutable3 = Map.of(1, "A",
2, "B",
3, "C");
// immutable3.put(4, "D"); (X)
System.out.println("immutable3 = " + immutable3);
// List ์ปฌ๋ ์
์ ๋ถ๋ณ ์ปฌ๋ ์
์ผ๋ก ๋ณต์ฌ
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
System.out.println("list = " + list);
List<String> immutableList = List.copyOf(list);
// immutableList.add("D"); (X)
System.out.println("immutableList = " + immutableList);
// Set ์ปฌ๋ ์
์ ๋ถ๋ณ ์ปฌ๋ ์
์ผ๋ก ๋ณต์ฌ
Set<String> set = new HashSet<>();
set.add("A");
set.add("B");
set.add("C");
System.out.println("set = " + set);
Set<String> immutableSet = Set.copyOf(set);
System.out.println("immutableSet = " + immutableSet);
// Map ์ปฌ๋ ์
์ ๋ถ๋ณ ์ปฌ๋ ์
์ผ๋ก ๋ณต์ฌ
Map<Integer, String> map = new HashMap<>();
map.put(1, "A");
map.put(2, "B");
map.put(3, "C");
System.out.println("map = " + map);
Map<Integer, String> immutableMap = Map.copyOf(map);
System.out.println("immutableMap = " + immutableMap);
// ๋ฐฐ์ด๋ก๋ถํฐ List ๋ถ๋ณ ์ปฌ๋ ์
์์ฑ
String[] arr = {"A", "B", "C"};
System.out.println("arr = " + Arrays.toString(arr));
List<String> stringList = Arrays.asList(arr);
System.out.println("stringList = " + stringList);
}
}