1 package org.djutils.immutablecollections;
2
3 import java.util.HashSet;
4 import java.util.Map;
5 import java.util.Set;
6
7 import org.djutils.exceptions.Throw;
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 public abstract class ImmutableAbstractMap<K, V> implements ImmutableMap<K, V>
24 {
25
26 private static final long serialVersionUID = 20160507L;
27
28
29 private final Map<K, V> map;
30
31
32 protected final Immutable copyOrWrap;
33
34
35 protected ImmutableCollection<V> cachedValues = null;
36
37
38
39
40
41
42
43 protected ImmutableAbstractMap(final Map<K, V> map, final Immutable copyOrWrap)
44 {
45 Throw.whenNull(copyOrWrap, "the copyOrWrap argument should be Immutable.COPY or Immutable.WRAP");
46 this.copyOrWrap = copyOrWrap;
47 Throw.whenNull(map, "the map argument cannot be null");
48 this.map = map;
49 }
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64 @SuppressWarnings("checkstyle:designforextension")
65 protected Map<K, V> getMap()
66 {
67 return this.map;
68 }
69
70
71 @Override
72 public final int size()
73 {
74 return this.map.size();
75 }
76
77
78 @Override
79 public final boolean isEmpty()
80 {
81 return this.map.isEmpty();
82 }
83
84
85 @Override
86 public final boolean containsKey(final Object key)
87 {
88 return this.map.containsKey(key);
89 }
90
91
92 @Override
93 public final boolean containsValue(final Object value)
94 {
95 return this.map.containsValue(value);
96 }
97
98
99 @Override
100 public final V get(final Object key)
101 {
102 return this.map.get(key);
103 }
104
105
106 @Override
107 public ImmutableCollection<V> values()
108 {
109 if (this.cachedValues == null)
110 {
111 Set<V> immutableValues = new HashSet<>(getMap().values());
112 this.cachedValues = new ImmutableHashSet<>(immutableValues, Immutable.WRAP);
113 }
114 return this.cachedValues;
115 }
116
117
118 @Override
119 public final boolean isWrap()
120 {
121 return this.copyOrWrap.isWrap();
122 }
123
124
125 @Override
126 @SuppressWarnings("checkstyle:designforextension")
127 public int hashCode()
128 {
129 final int prime = 31;
130 int result = 1;
131 result = prime * result + ((this.map == null) ? 0 : this.map.hashCode());
132 return result;
133 }
134
135
136 @Override
137 @SuppressWarnings({"checkstyle:designforextension", "checkstyle:needbraces"})
138 public boolean equals(final Object obj)
139 {
140 if (this == obj)
141 return true;
142 if (obj == null)
143 return false;
144 if (getClass() != obj.getClass())
145 return false;
146 ImmutableAbstractMap<?, ?> other = (ImmutableAbstractMap<?, ?>) obj;
147 if (this.map == null)
148 {
149 if (other.map != null)
150 return false;
151 }
152 else if (!this.map.equals(other.map))
153 return false;
154 return true;
155 }
156
157
158 @Override
159 @SuppressWarnings("checkstyle:designforextension")
160 public String toString()
161 {
162 return "Immutable[" + this.map.toString() + "]";
163 }
164 }