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