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