1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.surefire.api.util.internal;
20
21 import java.util.AbstractMap;
22 import java.util.LinkedHashSet;
23 import java.util.Map;
24 import java.util.Set;
25
26 import static java.util.Collections.unmodifiableSet;
27
28
29
30
31
32
33
34
35
36 public final class ImmutableMap<K, V> extends AbstractMap<K, V> {
37 private final Node<K, V> first;
38
39 public ImmutableMap(Map<K, V> map) {
40 Node<K, V> first = null;
41 Node<K, V> previous = null;
42 for (Entry<K, V> e : map.entrySet()) {
43 Node<K, V> node = new Node<>(e.getKey(), e.getValue());
44 if (first == null) {
45 first = node;
46 } else {
47 previous.next = node;
48 }
49 previous = node;
50 }
51 this.first = first;
52 }
53
54 @Override
55 public Set<Entry<K, V>> entrySet() {
56 Set<Entry<K, V>> entries = new LinkedHashSet<>();
57 Node<K, V> node = first;
58 while (node != null) {
59 entries.add(node);
60 node = node.next;
61 }
62 return unmodifiableSet(entries);
63 }
64
65 static final class Node<K, V> implements Entry<K, V> {
66 final K key;
67 final V value;
68 volatile Node<K, V> next;
69
70 Node(K key, V value) {
71 this.key = key;
72 this.value = value;
73 }
74
75 @Override
76 public K getKey() {
77 return key;
78 }
79
80 @Override
81 public V getValue() {
82 return value;
83 }
84
85 @Override
86 public V setValue(V value) {
87 throw new UnsupportedOperationException();
88 }
89
90 @Override
91 public boolean equals(Object o) {
92 if (this == o) {
93 return true;
94 }
95
96 if (o == null || getClass() != o.getClass()) {
97 return false;
98 }
99
100 Node<?, ?> node = (Node<?, ?>) o;
101
102 return getKey() != null
103 ? getKey().equals(node.getKey())
104 : node.getKey() == null && getValue() != null
105 ? getValue().equals(node.getValue())
106 : node.getValue() == null;
107 }
108
109 @Override
110 public int hashCode() {
111 int result = getKey() != null ? getKey().hashCode() : 0;
112 result = 31 * result + (getValue() != null ? getValue().hashCode() : 0);
113 return result;
114 }
115 }
116 }