001/*
002 * Copyright (C) 2007 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.base.Preconditions.checkNotNull;
020
021import com.google.common.annotations.GwtCompatible;
022import com.google.common.annotations.GwtIncompatible;
023import com.google.errorprone.annotations.CanIgnoreReturnValue;
024import java.io.IOException;
025import java.io.ObjectInputStream;
026import java.io.ObjectOutputStream;
027import java.util.EnumMap;
028import java.util.HashMap;
029import java.util.Map;
030import javax.annotation.Nullable;
031
032/**
033 * A {@code BiMap} backed by an {@code EnumMap} instance for keys-to-values, and
034 * a {@code HashMap} instance for values-to-keys. Null keys are not permitted,
035 * but null values are. An {@code EnumHashBiMap} and its inverse are both
036 * serializable.
037 *
038 * <p>See the Guava User Guide article on <a href=
039 * "https://github.com/google/guava/wiki/NewCollectionTypesExplained#bimap">
040 * {@code BiMap}</a>.
041 *
042 * @author Mike Bostock
043 * @since 2.0
044 */
045@GwtCompatible(emulated = true)
046public final class EnumHashBiMap<K extends Enum<K>, V> extends AbstractBiMap<K, V> {
047  private transient Class<K> keyType;
048
049  /**
050   * Returns a new, empty {@code EnumHashBiMap} using the specified key type.
051   *
052   * @param keyType the key type
053   */
054  public static <K extends Enum<K>, V> EnumHashBiMap<K, V> create(Class<K> keyType) {
055    return new EnumHashBiMap<>(keyType);
056  }
057
058  /**
059   * Constructs a new bimap with the same mappings as the specified map. If the
060   * specified map is an {@code EnumHashBiMap} or an {@link EnumBiMap}, the new
061   * bimap has the same key type as the input bimap. Otherwise, the specified
062   * map must contain at least one mapping, in order to determine the key type.
063   *
064   * @param map the map whose mappings are to be placed in this map
065   * @throws IllegalArgumentException if map is not an {@code EnumBiMap} or an
066   *     {@code EnumHashBiMap} instance and contains no mappings
067   */
068  public static <K extends Enum<K>, V> EnumHashBiMap<K, V> create(Map<K, ? extends V> map) {
069    EnumHashBiMap<K, V> bimap = create(EnumBiMap.inferKeyType(map));
070    bimap.putAll(map);
071    return bimap;
072  }
073
074  private EnumHashBiMap(Class<K> keyType) {
075    super(
076        WellBehavedMap.wrap(new EnumMap<K, V>(keyType)),
077        Maps.<V, K>newHashMapWithExpectedSize(keyType.getEnumConstants().length));
078    this.keyType = keyType;
079  }
080
081  // Overriding these 3 methods to show that values may be null (but not keys)
082
083  @Override
084  K checkKey(K key) {
085    return checkNotNull(key);
086  }
087
088  @CanIgnoreReturnValue
089  @Override
090  public V put(K key, @Nullable V value) {
091    return super.put(key, value);
092  }
093
094  @CanIgnoreReturnValue
095  @Override
096  public V forcePut(K key, @Nullable V value) {
097    return super.forcePut(key, value);
098  }
099
100  /** Returns the associated key type. */
101  public Class<K> keyType() {
102    return keyType;
103  }
104
105  /**
106   * @serialData the key class, number of entries, first key, first value,
107   *     second key, second value, and so on.
108   */
109  @GwtIncompatible // java.io.ObjectOutputStream
110  private void writeObject(ObjectOutputStream stream) throws IOException {
111    stream.defaultWriteObject();
112    stream.writeObject(keyType);
113    Serialization.writeMap(this, stream);
114  }
115
116  @SuppressWarnings("unchecked") // reading field populated by writeObject
117  @GwtIncompatible // java.io.ObjectInputStream
118  private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
119    stream.defaultReadObject();
120    keyType = (Class<K>) stream.readObject();
121    setDelegates(
122        WellBehavedMap.wrap(new EnumMap<K, V>(keyType)),
123        new HashMap<V, K>(keyType.getEnumConstants().length * 3 / 2));
124    Serialization.populateMap(this, stream);
125  }
126
127  @GwtIncompatible // only needed in emulated source.
128  private static final long serialVersionUID = 0;
129}