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
17package com.google.common.collect;
18
19import com.google.common.annotations.GwtCompatible;
20
21import java.util.HashMap;
22import java.util.Map;
23
24import javax.annotation.Nullable;
25
26/**
27 * A {@link BiMap} backed by two {@link HashMap} instances. This implementation
28 * allows null keys and values. A {@code HashBiMap} and its inverse are both
29 * serializable.
30 *
31 * @author Mike Bostock
32 * @since 2.0 (imported from Google Collections Library)
33 */
34@GwtCompatible(emulated = true)
35public final class HashBiMap<K, V> extends AbstractBiMap<K, V> {
36
37  /**
38   * Returns a new, empty {@code HashBiMap} with the default initial capacity
39   * (16).
40   */
41  public static <K, V> HashBiMap<K, V> create() {
42    return new HashBiMap<K, V>();
43  }
44
45  /**
46   * Constructs a new, empty bimap with the specified expected size.
47   *
48   * @param expectedSize the expected number of entries
49   * @throws IllegalArgumentException if the specified expected size is
50   *     negative
51   */
52  public static <K, V> HashBiMap<K, V> create(int expectedSize) {
53    return new HashBiMap<K, V>(expectedSize);
54  }
55
56  /**
57   * Constructs a new bimap containing initial values from {@code map}. The
58   * bimap is created with an initial capacity sufficient to hold the mappings
59   * in the specified map.
60   */
61  public static <K, V> HashBiMap<K, V> create(
62      Map<? extends K, ? extends V> map) {
63    HashBiMap<K, V> bimap = create(map.size());
64    bimap.putAll(map);
65    return bimap;
66  }
67
68  private HashBiMap() {
69    super(new HashMap<K, V>(), new HashMap<V, K>());
70  }
71
72  private HashBiMap(int expectedSize) {
73    super(
74        Maps.<K, V>newHashMapWithExpectedSize(expectedSize),
75        Maps.<V, K>newHashMapWithExpectedSize(expectedSize));
76  }
77
78  // Override these two methods to show that keys and values may be null
79
80  @Override public V put(@Nullable K key, @Nullable V value) {
81    return super.put(key, value);
82  }
83
84  @Override public V forcePut(@Nullable K key, @Nullable V value) {
85    return super.forcePut(key, value);
86  }
87}
88
89