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