com.google.inject.internal.ImmutableMap Maven / Gradle / Ivy
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.inject.internal;
import java.io.Serializable;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
/**
* An immutable, hash-based {@link Map} with reliable user-specified iteration
* order. Does not permit null keys or values.
*
* Unlike {@link Collections#unmodifiableMap}, which is a view of a
* separate map which can still change, an instance of {@code ImmutableMap}
* contains its own data and will never change. {@code ImmutableMap} is
* convenient for {@code public static final} maps ("constant maps") and also
* lets you easily make a "defensive copy" of a map provided to your class by a
* caller.
*
*
Note: Although this class is not final, it cannot be subclassed as
* it has no public or protected constructors. Thus, instances of this class are
* guaranteed to be immutable.
*
* @see ImmutableList
* @see ImmutableSet
* @author Jesse Wilson
* @author Kevin Bourrillion
*/
@SuppressWarnings("serial") // we're overriding default serialization
public abstract class ImmutableMap
implements ConcurrentMap, Serializable {
private static final ImmutableMap, ?> EMPTY_IMMUTABLE_MAP
= new EmptyImmutableMap();
// TODO: restore prebuilder API? optimize, compare performance to HashMap
/**
* Returns the empty map. This map behaves and performs comparably to
* {@link Collections#emptyMap}, and is preferable mainly for consistency
* and maintainability of your code.
*/
// Casting to any type is safe because the set will never hold any elements.
@SuppressWarnings("unchecked")
public static ImmutableMap of() {
return (ImmutableMap) EMPTY_IMMUTABLE_MAP;
}
/**
* Returns an immutable map containing a single entry. This map behaves and
* performs comparably to {@link Collections#singletonMap} but will not accept
* a null key or value. It is preferable mainly for consistency and
* maintainability of your code.
*/
public static ImmutableMap of(K k1, V v1) {
return new SingletonImmutableMap(
Preconditions.checkNotNull(k1), Preconditions.checkNotNull(v1));
}
/**
* Returns an immutable map containing the given entries, in order.
*
* @throws IllegalArgumentException if duplicate keys are added
*/
public static ImmutableMap of(K k1, V v1, K k2, V v2) {
return new RegularImmutableMap(entryOf(k1, v1), entryOf(k2, v2));
}
/**
* Returns an immutable map containing the given entries, in order.
*
* @throws IllegalArgumentException if duplicate keys are added
*/
public static ImmutableMap of(
K k1, V v1, K k2, V v2, K k3, V v3) {
return new RegularImmutableMap(
entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3));
}
/**
* Returns an immutable map containing the given entries, in order.
*
* @throws IllegalArgumentException if duplicate keys are added
*/
public static ImmutableMap of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
return new RegularImmutableMap(
entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4));
}
/**
* Returns an immutable map containing the given entries, in order.
*
* @throws IllegalArgumentException if duplicate keys are added
*/
public static ImmutableMap of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
return new RegularImmutableMap(entryOf(k1, v1),
entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4), entryOf(k5, v5));
}
// looking for of() with > 5 entries? Use the builder instead.
/**
* Returns a new builder. The generated builder is equivalent to the builder
* created by the {@link Builder} constructor.
*/
public static Builder builder() {
return new Builder();
}
/**
* Verifies that {@code key} and {@code value} are non-null, and returns a new
* entry with those values.
*/
private static Entry entryOf(K key, V value) {
return Maps.immutableEntry(Preconditions.checkNotNull(key), Preconditions.checkNotNull(value));
}
/**
* A builder for creating immutable map instances, especially {@code public
* static final} maps ("constant maps"). Example: {@code
*
* static final ImmutableMap WORD_TO_INT =
* new ImmutableMap.Builder()
* .put("one", 1)
* .put("two", 2)
* .put("three", 3)
* .build();}
*
* For small immutable maps, the {@code ImmutableMap.of()} methods are
* even more convenient.
*
* Builder instances can be reused - it is safe to call {@link #build}
* multiple times to build multiple maps in series. Each map is a superset of
* the maps created before it.
*/
public static class Builder {
final List> entries = Lists.newArrayList();
/**
* Creates a new builder. The returned builder is equivalent to the builder
* generated by {@link ImmutableMap#builder}.
*/
public Builder() {}
/**
* Associates {@code key} with {@code value} in the built map. Duplicate
* keys are not allowed, and will cause {@link #build} to fail.
*/
public Builder put(K key, V value) {
entries.add(entryOf(key, value));
return this;
}
/**
* Associates all of {@code map's} keys and values in the built map.
* Duplicate keys are not allowed, and will cause {@link #build} to fail.
*
* @throws NullPointerException if any key or value in {@code map} is null
*/
public Builder putAll(Map extends K, ? extends V> map) {
for (Entry extends K, ? extends V> entry : map.entrySet()) {
put(entry.getKey(), entry.getValue());
}
return this;
}
// TODO: Should build() and the ImmutableBiMap version throw an
// IllegalStateException instead?
/**
* Returns a newly-created immutable map.
*
* @throws IllegalArgumentException if duplicate keys were added
*/
public ImmutableMap build() {
return fromEntryList(entries);
}
private static ImmutableMap fromEntryList(
List> entries) {
int size = entries.size();
switch (size) {
case 0:
return of();
case 1:
return new SingletonImmutableMap(Iterables.getOnlyElement(entries));
default:
Entry, ?>[] entryArray
= entries.toArray(new Entry, ?>[entries.size()]);
return new RegularImmutableMap(entryArray);
}
}
}
/**
* Returns an immutable map containing the same entries as {@code map}. If
* {@code map} somehow contains entries with duplicate keys (for example, if
* it is a {@code SortedMap} whose comparator is not consistent with
* equals), the results of this method are undefined.
*
* Note: Despite what the method name suggests, if {@code map} is an
* {@code ImmutableMap}, no copy will actually be performed, and the given map
* itself will be returned.
*
* @throws NullPointerException if any key or value in {@code map} is null
*/
public static ImmutableMap copyOf(
Map extends K, ? extends V> map) {
if (map instanceof ImmutableMap) {
@SuppressWarnings("unchecked") // safe since map is not writable
ImmutableMap kvMap = (ImmutableMap) map;
return kvMap;
}
int size = map.size();
switch (size) {
case 0:
return of();
case 1:
Map.Entry extends K, ? extends V> loneEntry
= Iterables.getOnlyElement(map.entrySet());
/*
* Must cast next line to (K) and (V) to avoid returning an
* ImmutableMap extends K, ? extends V>, which is incompatible
* with the return type ImmutableMap. (Eclipse will complain
* mightily about this line if there's no cast.)
*/
return of((K) loneEntry.getKey(), (V) loneEntry.getValue());
default:
Entry, ?>[] array = new Entry, ?>[size];
int i = 0;
for (Entry extends K, ? extends V> entry : map.entrySet()) {
/*
* See comment above re: extends K, ? extends V> to .
*/
array[i++] = entryOf((K) entry.getKey(), (V) entry.getValue());
}
return new RegularImmutableMap(array);
}
}
ImmutableMap() {}
/**
* Guaranteed to throw an exception and leave the map unmodified.
*
* @throws UnsupportedOperationException always
*/
public final V put(K k, V v) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the map unmodified.
*
* @throws UnsupportedOperationException always
*/
public final V remove(Object o) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the map unmodified.
*
* @throws UnsupportedOperationException always
*/
public final V putIfAbsent(K key, V value) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the map unmodified.
*
* @throws UnsupportedOperationException always
*/
public final boolean remove(Object key, Object value) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the map unmodified.
*
* @throws UnsupportedOperationException always
*/
public final boolean replace(K key, V oldValue, V newValue) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the map unmodified.
*
* @throws UnsupportedOperationException always
*/
public final V replace(K key, V value) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the map unmodified.
*
* @throws UnsupportedOperationException always
*/
public final void putAll(Map extends K, ? extends V> map) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the map unmodified.
*
* @throws UnsupportedOperationException always
*/
public final void clear() {
throw new UnsupportedOperationException();
}
// Overriding to mark it Nullable
public abstract boolean containsKey(@Nullable Object key);
// Overriding to mark it Nullable
public abstract boolean containsValue(@Nullable Object value);
// Overriding to mark it Nullable
public abstract V get(@Nullable Object key);
/**
* Returns an immutable set of the mappings in this map. The entries are in
* the same order as the parameters used to build this map.
*/
public abstract ImmutableSet> entrySet();
/**
* Returns an immutable set of the keys in this map. These keys are in
* the same order as the parameters used to build this map.
*/
public abstract ImmutableSet keySet();
/**
* Returns an immutable collection of the values in this map. The values are
* in the same order as the parameters used to build this map.
*/
public abstract ImmutableCollection values();
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
if (object instanceof Map) {
Map, ?> that = (Map, ?>) object;
return this.entrySet().equals(that.entrySet());
}
return false;
}
@Override public int hashCode() {
// not caching hash code since it could change if map values are mutable
// in a way that modifies their hash codes
return entrySet().hashCode();
}
@Override public String toString() {
StringBuilder result = new StringBuilder(size() * 16).append('{');
Iterator> entries = entrySet().iterator();
result.append(entries.next());
while (entries.hasNext()) {
result.append(", ").append(entries.next());
}
return result.append('}').toString();
}
private static final class EmptyImmutableMap
extends ImmutableMap