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
017package com.google.common.collect;
018
019import com.google.common.annotations.Beta;
020import com.google.common.annotations.GwtCompatible;
021
022import java.util.Arrays;
023import java.util.Comparator;
024import java.util.Map;
025
026/**
027 * A {@link BiMap} whose contents will never change, with many other important properties detailed
028 * at {@link ImmutableCollection}.
029 *
030 * @author Jared Levy
031 * @since 2.0
032 */
033@GwtCompatible(serializable = true, emulated = true)
034public abstract class ImmutableBiMap<K, V> extends ImmutableMap<K, V> implements BiMap<K, V> {
035
036  /**
037   * Returns the empty bimap.
038   */
039  // Casting to any type is safe because the set will never hold any elements.
040  @SuppressWarnings("unchecked")
041  public static <K, V> ImmutableBiMap<K, V> of() {
042    return (ImmutableBiMap<K, V>) RegularImmutableBiMap.EMPTY;
043  }
044
045  /**
046   * Returns an immutable bimap containing a single entry.
047   */
048  public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1) {
049    return new SingletonImmutableBiMap<K, V>(k1, v1);
050  }
051
052  /**
053   * Returns an immutable map containing the given entries, in order.
054   *
055   * @throws IllegalArgumentException if duplicate keys or values are added
056   */
057  public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1, K k2, V v2) {
058    return RegularImmutableBiMap.fromEntries(entryOf(k1, v1), entryOf(k2, v2));
059  }
060
061  /**
062   * Returns an immutable map containing the given entries, in order.
063   *
064   * @throws IllegalArgumentException if duplicate keys or values are added
065   */
066  public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) {
067    return RegularImmutableBiMap.fromEntries(entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3));
068  }
069
070  /**
071   * Returns an immutable map containing the given entries, in order.
072   *
073   * @throws IllegalArgumentException if duplicate keys or values are added
074   */
075  public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
076    return RegularImmutableBiMap.fromEntries(
077        entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4));
078  }
079
080  /**
081   * Returns an immutable map containing the given entries, in order.
082   *
083   * @throws IllegalArgumentException if duplicate keys or values are added
084   */
085  public static <K, V> ImmutableBiMap<K, V> of(
086      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
087    return RegularImmutableBiMap.fromEntries(
088        entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4), entryOf(k5, v5));
089  }
090
091  // looking for of() with > 5 entries? Use the builder instead.
092
093  /**
094   * Returns a new builder. The generated builder is equivalent to the builder
095   * created by the {@link Builder} constructor.
096   */
097  public static <K, V> Builder<K, V> builder() {
098    return new Builder<K, V>();
099  }
100
101  /**
102   * A builder for creating immutable bimap instances, especially {@code public
103   * static final} bimaps ("constant bimaps"). Example: <pre>   {@code
104   *
105   *   static final ImmutableBiMap<String, Integer> WORD_TO_INT =
106   *       new ImmutableBiMap.Builder<String, Integer>()
107   *           .put("one", 1)
108   *           .put("two", 2)
109   *           .put("three", 3)
110   *           .build();}</pre>
111   *
112   * <p>For <i>small</i> immutable bimaps, the {@code ImmutableBiMap.of()} methods
113   * are even more convenient.
114   *
115   * <p>Builder instances can be reused - it is safe to call {@link #build}
116   * multiple times to build multiple bimaps in series. Each bimap is a superset
117   * of the bimaps created before it.
118   *
119   * @since 2.0
120   */
121  public static final class Builder<K, V> extends ImmutableMap.Builder<K, V> {
122
123    /**
124     * Creates a new builder. The returned builder is equivalent to the builder
125     * generated by {@link ImmutableBiMap#builder}.
126     */
127    public Builder() {}
128
129    Builder(int size) {
130      super(size);
131    }
132
133    /**
134     * Associates {@code key} with {@code value} in the built bimap. Duplicate
135     * keys or values are not allowed, and will cause {@link #build} to fail.
136     */
137    @Override
138    public Builder<K, V> put(K key, V value) {
139      super.put(key, value);
140      return this;
141    }
142
143    /**
144     * Adds the given {@code entry} to the bimap.  Duplicate keys or values
145     * are not allowed, and will cause {@link #build} to fail.
146     *
147     * @since 19.0
148     */
149    @Override
150    public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
151      super.put(entry);
152      return this;
153    }
154
155    /**
156     * Associates all of the given map's keys and values in the built bimap.
157     * Duplicate keys or values are not allowed, and will cause {@link #build}
158     * to fail.
159     *
160     * @throws NullPointerException if any key or value in {@code map} is null
161     */
162    @Override
163    public Builder<K, V> putAll(Map<? extends K, ? extends V> map) {
164      super.putAll(map);
165      return this;
166    }
167
168    /**
169     * Adds all of the given entries to the built bimap.  Duplicate keys or
170     * values are not allowed, and will cause {@link #build} to fail.
171     *
172     * @throws NullPointerException if any key, value, or entry is null
173     * @since 19.0
174     */
175    @Beta
176    @Override
177    public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
178      super.putAll(entries);
179      return this;
180    }
181
182    /**
183     * Configures this {@code Builder} to order entries by value according to the specified
184     * comparator.
185     *
186     * <p>The sort order is stable, that is, if two entries have values that compare
187     * as equivalent, the entry that was inserted first will be first in the built map's
188     * iteration order.
189     *
190     * @throws IllegalStateException if this method was already called
191     * @since 19.0
192     */
193    @Beta
194    @Override
195    public Builder<K, V> orderEntriesByValue(Comparator<? super V> valueComparator) {
196      super.orderEntriesByValue(valueComparator);
197      return this;
198    }
199
200    /**
201     * Returns a newly-created immutable bimap.
202     *
203     * @throws IllegalArgumentException if duplicate keys or values were added
204     */
205    @Override
206    public ImmutableBiMap<K, V> build() {
207      switch (size) {
208        case 0:
209          return of();
210        case 1:
211          return of(entries[0].getKey(), entries[0].getValue());
212        default:
213          /*
214           * If entries is full, then this implementation may end up using the entries array
215           * directly and writing over the entry objects with non-terminal entries, but this is
216           * safe; if this Builder is used further, it will grow the entries array (so it can't
217           * affect the original array), and future build() calls will always copy any entry
218           * objects that cannot be safely reused.
219           */
220          if (valueComparator != null) {
221            if (entriesUsed) {
222              entries = ObjectArrays.arraysCopyOf(entries, size);
223            }
224            Arrays.sort(
225                entries,
226                0,
227                size,
228                Ordering.from(valueComparator).onResultOf(Maps.<V>valueFunction()));
229          }
230          entriesUsed = size == entries.length;
231          return RegularImmutableBiMap.fromEntryArray(size, entries);
232      }
233    }
234  }
235
236  /**
237   * Returns an immutable bimap containing the same entries as {@code map}. If
238   * {@code map} somehow contains entries with duplicate keys (for example, if
239   * it is a {@code SortedMap} whose comparator is not <i>consistent with
240   * equals</i>), the results of this method are undefined.
241   *
242   * <p>Despite the method name, this method attempts to avoid actually copying
243   * the data when it is safe to do so. The exact circumstances under which a
244   * copy will or will not be performed are undocumented and subject to change.
245   *
246   * @throws IllegalArgumentException if two keys have the same value
247   * @throws NullPointerException if any key or value in {@code map} is null
248   */
249  public static <K, V> ImmutableBiMap<K, V> copyOf(Map<? extends K, ? extends V> map) {
250    if (map instanceof ImmutableBiMap) {
251      @SuppressWarnings("unchecked") // safe since map is not writable
252      ImmutableBiMap<K, V> bimap = (ImmutableBiMap<K, V>) map;
253      // TODO(lowasser): if we need to make a copy of a BiMap because the
254      // forward map is a view, don't make a copy of the non-view delegate map
255      if (!bimap.isPartialView()) {
256        return bimap;
257      }
258    }
259    return copyOf(map.entrySet());
260  }
261
262  /**
263   * Returns an immutable bimap containing the given entries.
264   *
265   * @throws IllegalArgumentException if two keys have the same value or two
266   *         values have the same key
267   * @throws NullPointerException if any key, value, or entry is null
268   * @since 19.0
269   */
270  @Beta
271  public static <K, V> ImmutableBiMap<K, V> copyOf(
272      Iterable<? extends Entry<? extends K, ? extends V>> entries) {
273    @SuppressWarnings("unchecked") // we'll only be using getKey and getValue, which are covariant
274    Entry<K, V>[] entryArray = (Entry<K, V>[]) Iterables.toArray(entries, EMPTY_ENTRY_ARRAY);
275    switch (entryArray.length) {
276      case 0:
277        return of();
278      case 1:
279        Entry<K, V> entry = entryArray[0];
280        return of(entry.getKey(), entry.getValue());
281      default:
282        /*
283         * The current implementation will end up using entryArray directly, though it will write
284         * over the (arbitrary, potentially mutable) Entry objects actually stored in entryArray.
285         */
286        return RegularImmutableBiMap.fromEntries(entryArray);
287    }
288  }
289
290  ImmutableBiMap() {}
291
292  /**
293   * {@inheritDoc}
294   *
295   * <p>The inverse of an {@code ImmutableBiMap} is another
296   * {@code ImmutableBiMap}.
297   */
298  @Override
299  public abstract ImmutableBiMap<V, K> inverse();
300
301  /**
302   * Returns an immutable set of the values in this map. The values are in the
303   * same order as the parameters used to build this map.
304   */
305  @Override
306  public ImmutableSet<V> values() {
307    return inverse().keySet();
308  }
309
310  /**
311   * Guaranteed to throw an exception and leave the bimap unmodified.
312   *
313   * @throws UnsupportedOperationException always
314   * @deprecated Unsupported operation.
315   */
316  @Deprecated
317  @Override
318  public V forcePut(K key, V value) {
319    throw new UnsupportedOperationException();
320  }
321
322  /**
323   * Serialized type for all ImmutableBiMap instances. It captures the logical
324   * contents and they are reconstructed using public factory methods. This
325   * ensures that the implementation types remain as implementation details.
326   *
327   * Since the bimap is immutable, ImmutableBiMap doesn't require special logic
328   * for keeping the bimap and its inverse in sync during serialization, the way
329   * AbstractBiMap does.
330   */
331  private static class SerializedForm extends ImmutableMap.SerializedForm {
332    SerializedForm(ImmutableBiMap<?, ?> bimap) {
333      super(bimap);
334    }
335
336    @Override
337    Object readResolve() {
338      Builder<Object, Object> builder = new Builder<Object, Object>();
339      return createMap(builder);
340    }
341
342    private static final long serialVersionUID = 0;
343  }
344
345  @Override
346  Object writeReplace() {
347    return new SerializedForm(this);
348  }
349}