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