View Javadoc
1   /*
2    * Copyright (C) 2007 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package com.google.common.collect;
18  
19  import static com.google.common.base.Preconditions.checkNotNull;
20  
21  import com.google.common.annotations.GwtCompatible;
22  import com.google.common.annotations.GwtIncompatible;
23  import com.google.errorprone.annotations.CanIgnoreReturnValue;
24  import java.io.IOException;
25  import java.io.ObjectInputStream;
26  import java.io.ObjectOutputStream;
27  import java.util.EnumMap;
28  import java.util.HashMap;
29  import java.util.Map;
30  import javax.annotation.Nullable;
31  
32  /**
33   * A {@code BiMap} backed by an {@code EnumMap} instance for keys-to-values, and
34   * a {@code HashMap} instance for values-to-keys. Null keys are not permitted,
35   * but null values are. An {@code EnumHashBiMap} and its inverse are both
36   * serializable.
37   *
38   * <p>See the Guava User Guide article on <a href=
39   * "https://github.com/google/guava/wiki/NewCollectionTypesExplained#bimap">
40   * {@code BiMap}</a>.
41   *
42   * @author Mike Bostock
43   * @since 2.0
44   */
45  @GwtCompatible(emulated = true)
46  public final class EnumHashBiMap<K extends Enum<K>, V> extends AbstractBiMap<K, V> {
47    private transient Class<K> keyType;
48  
49    /**
50     * Returns a new, empty {@code EnumHashBiMap} using the specified key type.
51     *
52     * @param keyType the key type
53     */
54    public static <K extends Enum<K>, V> EnumHashBiMap<K, V> create(Class<K> keyType) {
55      return new EnumHashBiMap<>(keyType);
56    }
57  
58    /**
59     * Constructs a new bimap with the same mappings as the specified map. If the
60     * specified map is an {@code EnumHashBiMap} or an {@link EnumBiMap}, the new
61     * bimap has the same key type as the input bimap. Otherwise, the specified
62     * map must contain at least one mapping, in order to determine the key type.
63     *
64     * @param map the map whose mappings are to be placed in this map
65     * @throws IllegalArgumentException if map is not an {@code EnumBiMap} or an
66     *     {@code EnumHashBiMap} instance and contains no mappings
67     */
68    public static <K extends Enum<K>, V> EnumHashBiMap<K, V> create(Map<K, ? extends V> map) {
69      EnumHashBiMap<K, V> bimap = create(EnumBiMap.inferKeyType(map));
70      bimap.putAll(map);
71      return bimap;
72    }
73  
74    private EnumHashBiMap(Class<K> keyType) {
75      super(
76          WellBehavedMap.wrap(new EnumMap<K, V>(keyType)),
77          Maps.<V, K>newHashMapWithExpectedSize(keyType.getEnumConstants().length));
78      this.keyType = keyType;
79    }
80  
81    // Overriding these 3 methods to show that values may be null (but not keys)
82  
83    @Override
84    K checkKey(K key) {
85      return checkNotNull(key);
86    }
87  
88    @CanIgnoreReturnValue
89    @Override
90    public V put(K key, @Nullable V value) {
91      return super.put(key, value);
92    }
93  
94    @CanIgnoreReturnValue
95    @Override
96    public V forcePut(K key, @Nullable V value) {
97      return super.forcePut(key, value);
98    }
99  
100   /** Returns the associated key type. */
101   public Class<K> keyType() {
102     return keyType;
103   }
104 
105   /**
106    * @serialData the key class, number of entries, first key, first value,
107    *     second key, second value, and so on.
108    */
109   @GwtIncompatible // java.io.ObjectOutputStream
110   private void writeObject(ObjectOutputStream stream) throws IOException {
111     stream.defaultWriteObject();
112     stream.writeObject(keyType);
113     Serialization.writeMap(this, stream);
114   }
115 
116   @SuppressWarnings("unchecked") // reading field populated by writeObject
117   @GwtIncompatible // java.io.ObjectInputStream
118   private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
119     stream.defaultReadObject();
120     keyType = (Class<K>) stream.readObject();
121     setDelegates(
122         WellBehavedMap.wrap(new EnumMap<K, V>(keyType)),
123         new HashMap<V, K>(keyType.getEnumConstants().length * 3 / 2));
124     Serialization.populateMap(this, stream);
125   }
126 
127   @GwtIncompatible // only needed in emulated source.
128   private static final long serialVersionUID = 0;
129 }