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