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