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