1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.utils.datastructures;
14 import java.util.Arrays;
15 import java.util.Collection;
16 import java.util.Collections;
17 import java.util.Iterator;
19 import java.util.NoSuchElementException;
23 * A space-optimized immutable Map implementation.
26 * Both map keys and values are specified as separate typed arrays that must be
27 * equally sized. This provides for space-optimization by allowing reusable key
28 * array instances since the keys cannot be modified.
31 * The map should be considered immutable, but it does allow modification of a
32 * value for an existing key as this only changes the value, the key will remain
35 * @author Tuukka Lehtonen
37 * @param <K> key class
38 * @param <V> value class
40 public class ArrayMap<K, V> implements Map<K, V> {
44 Set<Map.Entry<K, V>> entrySet;
46 Collection<V> valueSet;
48 public static class ArrayMapBuilder<K2, V2> {
50 final private K2[] keys;
52 ArrayMapBuilder(K2[] keys) {
56 public ArrayMap<K2, V2> values(@SuppressWarnings("unchecked") V2 ... values) {
57 return new ArrayMap<K2, V2>(keys, values);
62 public static <K2, V2>ArrayMapBuilder<K2, V2> keys(@SuppressWarnings("unchecked") K2 ... keys) {
63 return new ArrayMapBuilder<K2, V2>(keys);
66 public static <K2, V2> ArrayMap<K2, V2> make(K2[] keys, @SuppressWarnings("unchecked") V2... values) {
67 return new ArrayMap<K2, V2>(keys, values);
71 * Constructs new ArrayMap based on a key and value array. Both arrays must
72 * be of the same size.
74 * @param keys key array
75 * @param values value array
76 * @throws IllegalArgumentException if the arrays are of different size
77 * @throws NullPointerException if either parameter is <code>null</code>
79 public ArrayMap(K[] keys, V[] values) {
80 // NPE is caught by this.
81 if (keys.length != values.length)
82 throw new IllegalArgumentException("key array size (" + keys.length + ") != value array size (" + values.length + ")");
88 public Set<Map.Entry<K, V>> entrySet() {
89 return (entrySet != null) ? entrySet : (entrySet = new EntrySet());
94 throw new UnsupportedOperationException();
98 public boolean containsKey(Object key) {
99 return keySet().contains(key);
103 public boolean containsValue(Object value) {
104 return values().contains(value);
108 public V get(Object key) {
110 for (int i = 0; i < keys.length; i++) {
111 if (keys[i] == null) {
117 int hash = key.hashCode();
118 for (int i = 0; i < keys.length; i++) {
120 if (k == key || (hash == k.hashCode() && key.equals(k))) {
128 public boolean isEmpty() {
129 return keys.length == 0;
133 public Set<K> keySet() {
134 return (keySet != null) ? keySet : (keySet = new KeySet());
138 public V put(K key, V value) {
140 for (int i = 0; i < keys.length; i++) {
141 if (keys[i] == null) {
147 throw new UnsupportedOperationException("key " + key + " not present in ArrayMap");
149 int hash = key.hashCode();
150 for (int i = 0; i < keys.length; i++) {
152 if (k == key || (hash == k.hashCode() && key.equals(k))) {
158 throw new UnsupportedOperationException("key " + key + " not present in ArrayMap");
162 public void putAll(Map<? extends K, ? extends V> m) {
163 for (K k : m.keySet()) {
165 throw new UnsupportedOperationException("key " + k + " not present in ArrayMap");
167 for (Map.Entry<? extends K, ? extends V> entry : m.entrySet()) {
168 put(entry.getKey(), entry.getValue());
173 public V remove(Object key) {
174 throw new UnsupportedOperationException();
183 public Collection<V> values() {
184 return valueSet != null ? valueSet : (valueSet = Collections.unmodifiableCollection(Arrays.asList(values)));
187 class KeySet extends ImmutableSet<K> implements Set<K> {
190 public boolean contains(Object o) {
197 int hash = o.hashCode();
199 if (o == k || (hash == k.hashCode() && o.equals(k)))
205 public boolean containsAll(Collection<?> c) {
213 public boolean isEmpty() {
214 return keys.length == 0;
218 public Iterator<K> iterator() {
219 return new ImmutableIterator<K>() {
223 public boolean hasNext() {
224 return i < keys.length;
229 if (i >= keys.length)
230 throw new NoSuchElementException("no more elements (" + keys.length + " walked)");
244 public Object[] toArray() {
248 @SuppressWarnings("unchecked")
250 public <T> T[] toArray(T[] a) {
251 if (a.length < keys.length)
252 // Make a new array of a's runtime type, but my contents:
253 return (T[]) Arrays.copyOf(keys, keys.length, a.getClass());
254 System.arraycopy(keys, 0, a, 0, keys.length);
255 if (a.length > keys.length)
256 a[keys.length] = null;
261 class EntrySet extends ImmutableSet<Map.Entry<K, V>> implements Set<Map.Entry<K, V>> {
264 public boolean contains(Object o) {
265 throw new UnsupportedOperationException("TODO");
269 public boolean containsAll(Collection<?> c) {
277 public boolean isEmpty() {
278 return keys.length == 0;
282 public Iterator<Map.Entry<K, V>> iterator() {
283 return new ImmutableIterator<Map.Entry<K, V>>() {
287 public boolean hasNext() {
288 return i < keys.length;
292 public Map.Entry<K, V> next() {
293 if (i >= keys.length)
294 throw new NoSuchElementException("no more elements (" + keys.length + " walked)");
295 Map.Entry<K, V> entry = new ArrayMapEntry<K, V>(i, keys[i], values[i]);
310 * Returns the hash code value for this map. The hash code of a map is
311 * defined to be the sum of the hash codes of each entry in the map's
312 * <tt>entrySet()</tt> view. This ensures that <tt>m1.equals(m2)</tt>
313 * implies that <tt>m1.hashCode()==m2.hashCode()</tt> for any two maps
314 * <tt>m1</tt> and <tt>m2</tt>, as required by the general contract of
315 * {@link Object#hashCode}.
317 * <p>This implementation iterates over <tt>entrySet()</tt>, calling
318 * {@link Map.Entry#hashCode hashCode()} on each element (entry) in the
319 * set, and adding up the results.
321 * @return the hash code value for this map
322 * @see Map.Entry#hashCode()
323 * @see Object#equals(Object)
324 * @see Set#equals(Object)
327 public int hashCode() {
330 for (int i = 0; i < l; i++) {
333 int hash = (key==null ? 0 : key.hashCode()) ^ (value==null ? 0 : value.hashCode());
340 * Compares the specified object with this map for equality. Returns
341 * <tt>true</tt> if the given object is also a map and the two maps
342 * represent the same mappings. More formally, two maps <tt>m1</tt> and
343 * <tt>m2</tt> represent the same mappings if
344 * <tt>m1.entrySet().equals(m2.entrySet())</tt>. This ensures that the
345 * <tt>equals</tt> method works properly across different implementations
346 * of the <tt>Map</tt> interface.
348 * <p>This implementation first checks if the specified object is this map;
349 * if so it returns <tt>true</tt>. Then, it checks if the specified
350 * object is a map whose size is identical to the size of this map; if
351 * not, it returns <tt>false</tt>. If so, it iterates over this map's
352 * <tt>entrySet</tt> collection, and checks that the specified map
353 * contains each mapping that this map contains. If the specified map
354 * fails to contain such a mapping, <tt>false</tt> is returned. If the
355 * iteration completes, <tt>true</tt> is returned.
357 * @param o object to be compared for equality with this map
358 * @return <tt>true</tt> if the specified object is equal to this map
361 @SuppressWarnings("unchecked")
362 public boolean equals(Object o) {
366 if (!(o instanceof Map))
368 Map<K, V> m = (Map<K, V>) o;
369 if (m.size() != size())
374 for (int i = 0; i < l; i++) {
378 if (!(m.get(key)==null && m.containsKey(key)))
381 if (!value.equals(m.get(key)))
385 } catch (ClassCastException unused) {
387 } catch (NullPointerException unused) {
395 public String toString() {
396 Iterator<Map.Entry<K,V>> i = entrySet().iterator();
400 StringBuilder sb = new StringBuilder();
403 Map.Entry<K,V> e = i.next();
405 V value = e.getValue();
406 sb.append(key == this ? "(this Map)" : key);
408 sb.append(value == this ? "(this Map)" : value);
410 return sb.append('}').toString();