001/* 002 * Copyright (C) 2008 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 017package com.google.common.collect; 018 019import static com.google.common.collect.CollectPreconditions.checkEntryNotNull; 020 021import com.google.common.annotations.Beta; 022import com.google.common.annotations.GwtCompatible; 023import com.google.errorprone.annotations.CanIgnoreReturnValue; 024import java.util.Collection; 025import java.util.Comparator; 026import java.util.Map; 027 028/** 029 * A {@link BiMap} whose contents will never change, with many other important properties detailed 030 * at {@link ImmutableCollection}. 031 * 032 * @author Jared Levy 033 * @since 2.0 034 */ 035@GwtCompatible(serializable = true, emulated = true) 036public abstract class ImmutableBiMap<K, V> extends ImmutableMap<K, V> implements BiMap<K, V> { 037 038 /** 039 * Returns the empty bimap. 040 */ 041 // Casting to any type is safe because the set will never hold any elements. 042 @SuppressWarnings("unchecked") 043 public static <K, V> ImmutableBiMap<K, V> of() { 044 return (ImmutableBiMap<K, V>) RegularImmutableBiMap.EMPTY; 045 } 046 047 /** 048 * Returns an immutable bimap containing a single entry. 049 */ 050 public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1) { 051 checkEntryNotNull(k1, v1); 052 return new RegularImmutableBiMap<K, V>(new Object[] {k1, v1}, 1); 053 } 054 055 /** 056 * Returns an immutable map containing the given entries, in order. 057 * 058 * @throws IllegalArgumentException if duplicate keys or values are added 059 */ 060 public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1, K k2, V v2) { 061 checkEntryNotNull(k1, v1); 062 checkEntryNotNull(k2, v2); 063 return new RegularImmutableBiMap<K, V>(new Object[] {k1, v1, k2, v2}, 2); 064 } 065 066 /** 067 * Returns an immutable map containing the given entries, in order. 068 * 069 * @throws IllegalArgumentException if duplicate keys or values are added 070 */ 071 public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) { 072 checkEntryNotNull(k1, v1); 073 checkEntryNotNull(k2, v2); 074 checkEntryNotNull(k3, v3); 075 return new RegularImmutableBiMap<K, V>( 076 new Object[] {k1, v1, k2, v2, k3, v3}, 3); 077 } 078 079 /** 080 * Returns an immutable map containing the given entries, in order. 081 * 082 * @throws IllegalArgumentException if duplicate keys or values are added 083 */ 084 public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { 085 checkEntryNotNull(k1, v1); 086 checkEntryNotNull(k2, v2); 087 checkEntryNotNull(k3, v3); 088 checkEntryNotNull(k4, v4); 089 return new RegularImmutableBiMap<K, V>( 090 new Object[] {k1, v1, k2, v2, k3, v3, k4, v4}, 4); 091 } 092 093 /** 094 * Returns an immutable map containing the given entries, in order. 095 * 096 * @throws IllegalArgumentException if duplicate keys or values are added 097 */ 098 public static <K, V> ImmutableBiMap<K, V> of( 099 K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { 100 checkEntryNotNull(k1, v1); 101 checkEntryNotNull(k2, v2); 102 checkEntryNotNull(k3, v3); 103 checkEntryNotNull(k4, v4); 104 checkEntryNotNull(k5, v5); 105 return new RegularImmutableBiMap<K, V>( 106 new Object[] {k1, v1, k2, v2, k3, v3, k4, v4, k5, v5}, 5); 107 } 108 109 // looking for of() with > 5 entries? Use the builder instead. 110 111 /** 112 * Returns a new builder. The generated builder is equivalent to the builder 113 * created by the {@link Builder} constructor. 114 */ 115 public static <K, V> Builder<K, V> builder() { 116 return new Builder<K, V>(); 117 } 118 119 /** 120 * A builder for creating immutable bimap instances, especially {@code public 121 * static final} bimaps ("constant bimaps"). Example: <pre> {@code 122 * 123 * static final ImmutableBiMap<String, Integer> WORD_TO_INT = 124 * new ImmutableBiMap.Builder<String, Integer>() 125 * .put("one", 1) 126 * .put("two", 2) 127 * .put("three", 3) 128 * .build();}</pre> 129 * 130 * <p>For <i>small</i> immutable bimaps, the {@code ImmutableBiMap.of()} methods 131 * are even more convenient. 132 * 133 * <p>Builder instances can be reused - it is safe to call {@link #build} 134 * multiple times to build multiple bimaps in series. Each bimap is a superset 135 * of the bimaps created before it. 136 * 137 * @since 2.0 138 */ 139 public static final class Builder<K, V> extends ImmutableMap.Builder<K, V> { 140 /** 141 * Creates a new builder. The returned builder is equivalent to the builder 142 * generated by {@link ImmutableBiMap#builder}. 143 */ 144 public Builder() { 145 super(); 146 } 147 148 Builder(int size) { 149 super(size); 150 } 151 152 /** 153 * Associates {@code key} with {@code value} in the built bimap. Duplicate 154 * keys or values are not allowed, and will cause {@link #build} to fail. 155 */ 156 @CanIgnoreReturnValue 157 @Override 158 public Builder<K, V> put(K key, V value) { 159 super.put(key, value); 160 return this; 161 } 162 163 /** 164 * Adds the given {@code entry} to the bimap. Duplicate keys or values 165 * are not allowed, and will cause {@link #build} to fail. 166 * 167 * @since 19.0 168 */ 169 @CanIgnoreReturnValue 170 @Override 171 public Builder<K, V> put(Entry<? extends K, ? extends V> entry) { 172 super.put(entry); 173 return this; 174 } 175 176 /** 177 * Associates all of the given map's keys and values in the built bimap. 178 * Duplicate keys or values are not allowed, and will cause {@link #build} 179 * to fail. 180 * 181 * @throws NullPointerException if any key or value in {@code map} is null 182 */ 183 @CanIgnoreReturnValue 184 @Override 185 public Builder<K, V> putAll(Map<? extends K, ? extends V> map) { 186 super.putAll(map); 187 return this; 188 } 189 190 /** 191 * Adds all of the given entries to the built bimap. Duplicate keys or 192 * values are not allowed, and will cause {@link #build} to fail. 193 * 194 * @throws NullPointerException if any key, value, or entry is null 195 * @since 19.0 196 */ 197 @CanIgnoreReturnValue 198 @Beta 199 @Override 200 public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) { 201 super.putAll(entries); 202 return this; 203 } 204 205 /** 206 * Configures this {@code Builder} to order entries by value according to the specified 207 * comparator. 208 * 209 * <p>The sort order is stable, that is, if two entries have values that compare 210 * as equivalent, the entry that was inserted first will be first in the built map's 211 * iteration order. 212 * 213 * @throws IllegalStateException if this method was already called 214 * @since 19.0 215 */ 216 @CanIgnoreReturnValue 217 @Beta 218 @Override 219 public Builder<K, V> orderEntriesByValue(Comparator<? super V> valueComparator) { 220 super.orderEntriesByValue(valueComparator); 221 return this; 222 } 223 224 /** 225 * Returns a newly-created immutable bimap. 226 * 227 * @throws IllegalArgumentException if duplicate keys or values were added 228 */ 229 @Override 230 public ImmutableBiMap<K, V> build() { 231 if (size == 0) { 232 return of(); 233 } 234 sortEntries(); 235 entriesUsed = true; 236 return new RegularImmutableBiMap<K, V>(alternatingKeysAndValues, size); 237 } 238 } 239 240 /** 241 * Returns an immutable bimap containing the same entries as {@code map}. If 242 * {@code map} somehow contains entries with duplicate keys (for example, if 243 * it is a {@code SortedMap} whose comparator is not <i>consistent with 244 * equals</i>), the results of this method are undefined. 245 * 246 * <p>Despite the method name, this method attempts to avoid actually copying 247 * the data when it is safe to do so. The exact circumstances under which a 248 * copy will or will not be performed are undocumented and subject to change. 249 * 250 * @throws IllegalArgumentException if two keys have the same value 251 * @throws NullPointerException if any key or value in {@code map} is null 252 */ 253 public static <K, V> ImmutableBiMap<K, V> copyOf(Map<? extends K, ? extends V> map) { 254 if (map instanceof ImmutableBiMap) { 255 @SuppressWarnings("unchecked") // safe since map is not writable 256 ImmutableBiMap<K, V> bimap = (ImmutableBiMap<K, V>) map; 257 // TODO(lowasser): if we need to make a copy of a BiMap because the 258 // forward map is a view, don't make a copy of the non-view delegate map 259 if (!bimap.isPartialView()) { 260 return bimap; 261 } 262 } 263 return copyOf(map.entrySet()); 264 } 265 266 /** 267 * Returns an immutable bimap containing the given entries. 268 * 269 * @throws IllegalArgumentException if two keys have the same value or two 270 * values have the same key 271 * @throws NullPointerException if any key, value, or entry is null 272 * @since 19.0 273 */ 274 @Beta 275 public static <K, V> ImmutableBiMap<K, V> copyOf( 276 Iterable<? extends Entry<? extends K, ? extends V>> entries) { 277 int estimatedSize = 278 (entries instanceof Collection) 279 ? ((Collection<?>) entries).size() 280 : ImmutableCollection.Builder.DEFAULT_INITIAL_CAPACITY; 281 return new Builder<K, V>(estimatedSize).putAll(entries).build(); 282 } 283 284 ImmutableBiMap() {} 285 286 /** 287 * {@inheritDoc} 288 * 289 * <p>The inverse of an {@code ImmutableBiMap} is another 290 * {@code ImmutableBiMap}. 291 */ 292 @Override 293 public abstract ImmutableBiMap<V, K> inverse(); 294 295 /** 296 * Returns an immutable set of the values in this map. The values are in the 297 * same order as the parameters used to build this map. 298 */ 299 @Override 300 public ImmutableSet<V> values() { 301 return inverse().keySet(); 302 } 303 304 @Override 305 final ImmutableSet<V> createValues() { 306 throw new AssertionError("should never be called"); 307 } 308 309 /** 310 * Guaranteed to throw an exception and leave the bimap unmodified. 311 * 312 * @throws UnsupportedOperationException always 313 * @deprecated Unsupported operation. 314 */ 315 @CanIgnoreReturnValue 316 @Deprecated 317 @Override 318 public V forcePut(K key, V value) { 319 throw new UnsupportedOperationException(); 320 } 321 322 /** 323 * Serialized type for all ImmutableBiMap instances. It captures the logical 324 * contents and they are reconstructed using public factory methods. This 325 * ensures that the implementation types remain as implementation details. 326 * 327 * Since the bimap is immutable, ImmutableBiMap doesn't require special logic 328 * for keeping the bimap and its inverse in sync during serialization, the way 329 * AbstractBiMap does. 330 */ 331 private static class SerializedForm extends ImmutableMap.SerializedForm { 332 SerializedForm(ImmutableBiMap<?, ?> bimap) { 333 super(bimap); 334 } 335 336 @Override 337 Object readResolve() { 338 Builder<Object, Object> builder = new Builder<Object, Object>(); 339 return createMap(builder); 340 } 341 342 private static final long serialVersionUID = 0; 343 } 344 345 @Override 346 Object writeReplace() { 347 return new SerializedForm(this); 348 } 349}