001    /*
002     * Copyright (C) 2008 The Guava Authors
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    
017    package com.google.common.collect;
018    
019    import static com.google.common.base.Preconditions.checkNotNull;
020    import static com.google.common.collect.Iterables.getOnlyElement;
021    
022    import com.google.common.annotations.GwtCompatible;
023    
024    import java.io.Serializable;
025    import java.util.ArrayList;
026    import java.util.Collections;
027    import java.util.HashMap;
028    import java.util.List;
029    import java.util.Map;
030    
031    import javax.annotation.Nullable;
032    
033    /**
034     * An immutable, hash-based {@link Map} with reliable user-specified iteration
035     * order. Does not permit null keys or values.
036     *
037     * <p>Unlike {@link Collections#unmodifiableMap}, which is a <i>view</i> of a
038     * separate map which can still change, an instance of {@code ImmutableMap}
039     * contains its own data and will <i>never</i> change. {@code ImmutableMap} is
040     * convenient for {@code public static final} maps ("constant maps") and also
041     * lets you easily make a "defensive copy" of a map provided to your class by a
042     * caller.
043     *
044     * <p><i>Performance notes:</i> unlike {@link HashMap}, {@code ImmutableMap} is
045     * not optimized for element types that have slow {@link Object#equals} or
046     * {@link Object#hashCode} implementations. You can get better performance by
047     * having your element type cache its own hash codes, and by making use of the
048     * cached values to short-circuit a slow {@code equals} algorithm.
049     *
050     * @author Jesse Wilson
051     * @author Kevin Bourrillion
052     * @since 2 (imported from Google Collections Library)
053     */
054    @GwtCompatible(serializable = true, emulated = true)
055    @SuppressWarnings("serial") // we're overriding default serialization
056    public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable {
057      /**
058       * Returns the empty map. This map behaves and performs comparably to
059       * {@link Collections#emptyMap}, and is preferable mainly for consistency
060       * and maintainability of your code.
061       */
062      // Casting to any type is safe because the set will never hold any elements.
063      @SuppressWarnings("unchecked")
064      public static <K, V> ImmutableMap<K, V> of() {
065        return (ImmutableMap<K, V>) EmptyImmutableMap.INSTANCE;
066      }
067    
068      /**
069       * Returns an immutable map containing a single entry. This map behaves and
070       * performs comparably to {@link Collections#singletonMap} but will not accept
071       * a null key or value. It is preferable mainly for consistency and
072       * maintainability of your code.
073       */
074      public static <K, V> ImmutableMap<K, V> of(K k1, V v1) {
075        return new SingletonImmutableMap<K, V>(
076            checkNotNull(k1), checkNotNull(v1));
077      }
078    
079      /**
080       * Returns an immutable map containing the given entries, in order.
081       *
082       * @throws IllegalArgumentException if duplicate keys are provided
083       */
084      public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2) {
085        return new RegularImmutableMap<K, V>(entryOf(k1, v1), entryOf(k2, v2));
086      }
087    
088      /**
089       * Returns an immutable map containing the given entries, in order.
090       *
091       * @throws IllegalArgumentException if duplicate keys are provided
092       */
093      public static <K, V> ImmutableMap<K, V> of(
094          K k1, V v1, K k2, V v2, K k3, V v3) {
095        return new RegularImmutableMap<K, V>(
096            entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3));
097      }
098    
099      /**
100       * Returns an immutable map containing the given entries, in order.
101       *
102       * @throws IllegalArgumentException if duplicate keys are provided
103       */
104      public static <K, V> ImmutableMap<K, V> of(
105          K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
106        return new RegularImmutableMap<K, V>(
107            entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4));
108      }
109    
110      /**
111       * Returns an immutable map containing the given entries, in order.
112       *
113       * @throws IllegalArgumentException if duplicate keys are provided
114       */
115      public static <K, V> ImmutableMap<K, V> of(
116          K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
117        return new RegularImmutableMap<K, V>(entryOf(k1, v1),
118            entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4), entryOf(k5, v5));
119      }
120    
121      // looking for of() with > 5 entries? Use the builder instead.
122    
123      /**
124       * Returns a new builder. The generated builder is equivalent to the builder
125       * created by the {@link Builder} constructor.
126       */
127      public static <K, V> Builder<K, V> builder() {
128        return new Builder<K, V>();
129      }
130    
131      /**
132       * Verifies that {@code key} and {@code value} are non-null, and returns a new
133       * immutable entry with those values.
134       *
135       * <p>A call to {@link Map.Entry#setValue} on the returned entry will always
136       * throw {@link UnsupportedOperationException}.
137       */
138      static <K, V> Entry<K, V> entryOf(K key, V value) {
139        return Maps.immutableEntry(
140            checkNotNull(key, "null key"),
141            checkNotNull(value, "null value"));
142      }
143    
144      /**
145       * A builder for creating immutable map instances, especially {@code public
146       * static final} maps ("constant maps"). Example: <pre>   {@code
147       *
148       *   static final ImmutableMap<String, Integer> WORD_TO_INT =
149       *       new ImmutableMap.Builder<String, Integer>()
150       *           .put("one", 1)
151       *           .put("two", 2)
152       *           .put("three", 3)
153       *           .build();}</pre>
154       *
155       * For <i>small</i> immutable maps, the {@code ImmutableMap.of()} methods are
156       * even more convenient.
157       *
158       * <p>Builder instances can be reused - it is safe to call {@link #build}
159       * multiple times to build multiple maps in series. Each map is a superset of
160       * the maps created before it.
161       *
162       * @since 2 (imported from Google Collections Library)
163       */
164      public static class Builder<K, V> {
165        final ArrayList<Entry<K, V>> entries = Lists.newArrayList();
166    
167        /**
168         * Creates a new builder. The returned builder is equivalent to the builder
169         * generated by {@link ImmutableMap#builder}.
170         */
171        public Builder() {}
172    
173        /**
174         * Associates {@code key} with {@code value} in the built map. Duplicate
175         * keys are not allowed, and will cause {@link #build} to fail.
176         */
177        public Builder<K, V> put(K key, V value) {
178          entries.add(entryOf(key, value));
179          return this;
180        }
181    
182        /**
183         * Associates all of the given map's keys and values in the built map.
184         * Duplicate keys are not allowed, and will cause {@link #build} to fail.
185         *
186         * @throws NullPointerException if any key or value in {@code map} is null
187         */
188        public Builder<K, V> putAll(Map<? extends K, ? extends V> map) {
189          entries.ensureCapacity(entries.size() + map.size());
190          for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
191            put(entry.getKey(), entry.getValue());
192          }
193          return this;
194        }
195    
196        /*
197         * TODO(kevinb): Should build() and the ImmutableBiMap & ImmutableSortedMap
198         * versions throw an IllegalStateException instead?
199         */
200    
201        /**
202         * Returns a newly-created immutable map.
203         *
204         * @throws IllegalArgumentException if duplicate keys were added
205         */
206        public ImmutableMap<K, V> build() {
207          return fromEntryList(entries);
208        }
209    
210        private static <K, V> ImmutableMap<K, V> fromEntryList(
211            List<Entry<K, V>> entries) {
212          int size = entries.size();
213          switch (size) {
214            case 0:
215              return of();
216            case 1:
217              return new SingletonImmutableMap<K, V>(getOnlyElement(entries));
218            default:
219              Entry<?, ?>[] entryArray
220                  = entries.toArray(new Entry<?, ?>[entries.size()]);
221              return new RegularImmutableMap<K, V>(entryArray);
222          }
223        }
224      }
225    
226      /**
227       * Returns an immutable map containing the same entries as {@code map}. If
228       * {@code map} somehow contains entries with duplicate keys (for example, if
229       * it is a {@code SortedMap} whose comparator is not <i>consistent with
230       * equals</i>), the results of this method are undefined.
231       *
232       * <p>Despite the method name, this method attempts to avoid actually copying
233       * the data when it is safe to do so. The exact circumstances under which a
234       * copy will or will not be performed are undocumented and subject to change.
235       *
236       * @throws NullPointerException if any key or value in {@code map} is null
237       */
238      public static <K, V> ImmutableMap<K, V> copyOf(
239          Map<? extends K, ? extends V> map) {
240        if ((map instanceof ImmutableMap) && !(map instanceof ImmutableSortedMap)) {
241          // TODO(user): Make ImmutableMap.copyOf(immutableBiMap) call copyOf()
242          // on the ImmutableMap delegate(), rather than the bimap itself
243    
244          @SuppressWarnings("unchecked") // safe since map is not writable
245          ImmutableMap<K, V> kvMap = (ImmutableMap<K, V>) map;
246          if (!kvMap.isPartialView()) {
247            return kvMap;
248          }
249        }
250    
251        @SuppressWarnings("unchecked") // we won't write to this array
252        Entry<K, V>[] entries = map.entrySet().toArray(new Entry[0]);
253        switch (entries.length) {
254          case 0:
255            return of();
256          case 1:
257            return new SingletonImmutableMap<K, V>(entryOf(
258                entries[0].getKey(), entries[0].getValue()));
259          default:
260            for (int i = 0; i < entries.length; i++) {
261              K k = entries[i].getKey();
262              V v = entries[i].getValue();
263              entries[i] = entryOf(k, v);
264            }
265            return new RegularImmutableMap<K, V>(entries);
266        }
267      }
268    
269      ImmutableMap() {}
270    
271      /**
272       * Guaranteed to throw an exception and leave the map unmodified.
273       *
274       * @throws UnsupportedOperationException always
275       */
276      @Override
277      public final V put(K k, V v) {
278        throw new UnsupportedOperationException();
279      }
280    
281      /**
282       * Guaranteed to throw an exception and leave the map unmodified.
283       *
284       * @throws UnsupportedOperationException always
285       */
286      @Override
287      public final V remove(Object o) {
288        throw new UnsupportedOperationException();
289      }
290    
291      /**
292       * Guaranteed to throw an exception and leave the map unmodified.
293       *
294       * @throws UnsupportedOperationException always
295       */
296      @Override
297      public final void putAll(Map<? extends K, ? extends V> map) {
298        throw new UnsupportedOperationException();
299      }
300    
301      /**
302       * Guaranteed to throw an exception and leave the map unmodified.
303       *
304       * @throws UnsupportedOperationException always
305       */
306      @Override
307      public final void clear() {
308        throw new UnsupportedOperationException();
309      }
310    
311      @Override
312      public boolean isEmpty() {
313        return size() == 0;
314      }
315    
316      @Override
317      public boolean containsKey(@Nullable Object key) {
318        return get(key) != null;
319      }
320    
321      // Overriding to mark it Nullable
322      @Override
323      public abstract boolean containsValue(@Nullable Object value);
324    
325      // Overriding to mark it Nullable
326      @Override
327      public abstract V get(@Nullable Object key);
328    
329      /**
330       * Returns an immutable set of the mappings in this map. The entries are in
331       * the same order as the parameters used to build this map.
332       */
333      @Override
334      public abstract ImmutableSet<Entry<K, V>> entrySet();
335    
336      /**
337       * Returns an immutable set of the keys in this map. These keys are in
338       * the same order as the parameters used to build this map.
339       */
340      @Override
341      public abstract ImmutableSet<K> keySet();
342    
343      /**
344       * Returns an immutable collection of the values in this map. The values are
345       * in the same order as the parameters used to build this map.
346       */
347      @Override
348      public abstract ImmutableCollection<V> values();
349    
350      @Override public boolean equals(@Nullable Object object) {
351        if (object == this) {
352          return true;
353        }
354        if (object instanceof Map) {
355          Map<?, ?> that = (Map<?, ?>) object;
356          return this.entrySet().equals(that.entrySet());
357        }
358        return false;
359      }
360    
361      abstract boolean isPartialView();
362    
363      @Override public int hashCode() {
364        // not caching hash code since it could change if map values are mutable
365        // in a way that modifies their hash codes
366        return entrySet().hashCode();
367      }
368    
369      @Override public String toString() {
370        return Maps.toStringImpl(this);
371      }
372    
373      /**
374       * Serialized type for all ImmutableMap instances. It captures the logical
375       * contents and they are reconstructed using public factory methods. This
376       * ensures that the implementation types remain as implementation details.
377       */
378      static class SerializedForm implements Serializable {
379        private final Object[] keys;
380        private final Object[] values;
381        SerializedForm(ImmutableMap<?, ?> map) {
382          keys = new Object[map.size()];
383          values = new Object[map.size()];
384          int i = 0;
385          for (Entry<?, ?> entry : map.entrySet()) {
386            keys[i] = entry.getKey();
387            values[i] = entry.getValue();
388            i++;
389          }
390        }
391        Object readResolve() {
392          Builder<Object, Object> builder = new Builder<Object, Object>();
393          return createMap(builder);
394        }
395        Object createMap(Builder<Object, Object> builder) {
396          for (int i = 0; i < keys.length; i++) {
397            builder.put(keys[i], values[i]);
398          }
399          return builder.build();
400        }
401        private static final long serialVersionUID = 0;
402      }
403    
404      Object writeReplace() {
405        return new SerializedForm(this);
406      }
407    }