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