1 package org.djutils.immutablecollections;
2
3 import java.util.HashMap;
4 import java.util.HashSet;
5 import java.util.Map;
6 import java.util.Map.Entry;
7 import java.util.Set;
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 public class ImmutableHashMap<K, V> extends ImmutableAbstractMap<K, V>
23 {
24
25 private static final long serialVersionUID = 20160507L;
26
27
28 private ImmutableSet<K> cachedKeySet = null;
29
30
31 private ImmutableSet<ImmutableEntry<K, V>> cachedEntrySet = null;
32
33
34
35
36 public ImmutableHashMap(final Map<K, V> map)
37 {
38 super(new HashMap<K, V>(map), Immutable.COPY);
39 }
40
41
42
43
44
45 public ImmutableHashMap(final Map<K, V> map, final Immutable copyOrWrap)
46 {
47 super(copyOrWrap == Immutable.COPY ? new HashMap<K, V>(map) : map, copyOrWrap);
48 }
49
50
51
52
53 public ImmutableHashMap(final ImmutableAbstractMap<K, V> immutableMap)
54 {
55 super(new HashMap<K, V>(immutableMap.getUnderlyingMap()), Immutable.COPY);
56 }
57
58
59
60
61
62 public ImmutableHashMap(final ImmutableAbstractMap<K, V> immutableMap, final Immutable copyOrWrap)
63 {
64 super(copyOrWrap == Immutable.COPY ? new HashMap<K, V>(immutableMap.getUnderlyingMap())
65 : immutableMap.getUnderlyingMap(), copyOrWrap);
66 }
67
68 @Override
69 protected final Map<K, V> getUnderlyingMap()
70 {
71 return super.getUnderlyingMap();
72 }
73
74 @Override
75 public final Map<K, V> toMap()
76 {
77 return new HashMap<K, V>(getUnderlyingMap());
78 }
79
80 @Override
81 public final ImmutableSet<K> keySet()
82 {
83 if (this.cachedKeySet == null)
84 {
85 Set<K> immutableKeySet = new HashSet<>(getUnderlyingMap().keySet());
86 this.cachedKeySet = new ImmutableHashSet<>(immutableKeySet, Immutable.WRAP);
87 }
88 return this.cachedKeySet;
89 }
90
91 @Override
92 public ImmutableSet<ImmutableEntry<K, V>> entrySet()
93 {
94 if (this.cachedEntrySet == null)
95 {
96 Set<ImmutableEntry<K, V>> immutableEntrySet = new HashSet<>();
97 for (Entry<K, V> entry : getUnderlyingMap().entrySet())
98 {
99 immutableEntrySet.add(new ImmutableEntry<>(entry));
100 }
101 this.cachedEntrySet = new ImmutableHashSet<>(immutableEntrySet, Immutable.WRAP);
102 }
103 return this.cachedEntrySet;
104 }
105
106 @Override
107 @SuppressWarnings("checkstyle:designforextension")
108 public String toString()
109 {
110 Map<K, V> map = getUnderlyingMap();
111 if (null == map)
112 {
113 return "ImmutableHashMap []";
114 }
115 return "ImmutableHashMap [" + map.toString() + "]";
116 }
117
118 }