EnumMap.java revision 3323
0N/A/*
0N/A * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
0N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
0N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
0N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
0N/A * or visit www.oracle.com if you need additional information or have any
0N/A * questions.
0N/A */
0N/A
0N/Apackage java.util;
0N/A
0N/Aimport java.util.Map.Entry;
0N/Aimport sun.misc.SharedSecrets;
0N/A
0N/A/**
113N/A * A specialized {@link Map} implementation for use with enum type keys. All
113N/A * of the keys in an enum map must come from a single enum type that is
0N/A * specified, explicitly or implicitly, when the map is created. Enum maps
0N/A * are represented internally as arrays. This representation is extremely
0N/A * compact and efficient.
0N/A *
0N/A * <p>Enum maps are maintained in the <i>natural order</i> of their keys
0N/A * (the order in which the enum constants are declared). This is reflected
0N/A * in the iterators returned by the collections views ({@link #keySet()},
0N/A * {@link #entrySet()}, and {@link #values()}).
0N/A *
0N/A * <p>Iterators returned by the collection views are <i>weakly consistent</i>:
0N/A * they will never throw {@link ConcurrentModificationException} and they may
0N/A * or may not show the effects of any modifications to the map that occur while
0N/A * the iteration is in progress.
0N/A *
0N/A * <p>Null keys are not permitted. Attempts to insert a null key will
0N/A * throw {@link NullPointerException}. Attempts to test for the
0N/A * presence of a null key or to remove one will, however, function properly.
0N/A * Null values are permitted.
0N/A
0N/A * <P>Like most collection implementations <tt>EnumMap</tt> is not
0N/A * synchronized. If multiple threads access an enum map concurrently, and at
0N/A * least one of the threads modifies the map, it should be synchronized
0N/A * externally. This is typically accomplished by synchronizing on some
0N/A * object that naturally encapsulates the enum map. If no such object exists,
0N/A * the map should be "wrapped" using the {@link Collections#synchronizedMap}
0N/A * method. This is best done at creation time, to prevent accidental
0N/A * unsynchronized access:
0N/A *
0N/A * <pre>
0N/A * Map&lt;EnumKey, V&gt; m
0N/A * = Collections.synchronizedMap(new EnumMap&lt;EnumKey, V&gt;(...));
0N/A * </pre>
0N/A *
0N/A * <p>Implementation note: All basic operations execute in constant time.
0N/A * They are likely (though not guaranteed) to be faster than their
0N/A * {@link HashMap} counterparts.
0N/A *
0N/A * <p>This class is a member of the
103N/A * <a href="{@docRoot}/../technotes/guides/collections/index.html">
103N/A * Java Collections Framework</a>.
103N/A *
103N/A * @author Josh Bloch
103N/A * @see EnumSet
103N/A * @since 1.5
103N/A */
103N/Apublic class EnumMap<K extends Enum<K>, V> extends AbstractMap<K, V>
103N/A implements java.io.Serializable, Cloneable
103N/A{
103N/A /**
103N/A * The <tt>Class</tt> object for the enum type of all the keys of this map.
103N/A *
0N/A * @serial
0N/A */
0N/A private final Class<K> keyType;
0N/A
0N/A /**
0N/A * All of the values comprising K. (Cached for performance.)
0N/A */
0N/A private transient K[] keyUniverse;
0N/A
0N/A /**
0N/A * Array representation of this map. The ith element is the value
0N/A * to which universe[i] is currently mapped, or null if it isn't
0N/A * mapped to anything, or NULL if it's mapped to null.
0N/A */
0N/A private transient Object[] vals;
103N/A
103N/A /**
103N/A * The number of mappings in this map.
103N/A */
103N/A private transient int size = 0;
103N/A
103N/A /**
103N/A * Distinguished non-null value for representing null values.
103N/A */
103N/A private static final Object NULL = new Object();
103N/A
103N/A private Object maskNull(Object value) {
103N/A return (value == null ? NULL : value);
103N/A }
103N/A
0N/A private V unmaskNull(Object value) {
0N/A return (V) (value == NULL ? null : value);
0N/A }
0N/A
0N/A private static Enum[] ZERO_LENGTH_ENUM_ARRAY = new Enum[0];
0N/A
0N/A /**
0N/A * Creates an empty enum map with the specified key type.
0N/A *
0N/A * @param keyType the class object of the key type for this enum map
0N/A * @throws NullPointerException if <tt>keyType</tt> is null
0N/A */
0N/A public EnumMap(Class<K> keyType) {
0N/A this.keyType = keyType;
0N/A keyUniverse = getKeyUniverse(keyType);
0N/A vals = new Object[keyUniverse.length];
0N/A }
0N/A
0N/A /**
0N/A * Creates an enum map with the same key type as the specified enum
0N/A * map, initially containing the same mappings (if any).
0N/A *
0N/A * @param m the enum map from which to initialize this enum map
0N/A * @throws NullPointerException if <tt>m</tt> is null
0N/A */
0N/A public EnumMap(EnumMap<K, ? extends V> m) {
113N/A keyType = m.keyType;
113N/A keyUniverse = m.keyUniverse;
113N/A vals = m.vals.clone();
113N/A size = m.size;
113N/A }
113N/A
0N/A /**
0N/A * Creates an enum map initialized from the specified map. If the
0N/A * specified map is an <tt>EnumMap</tt> instance, this constructor behaves
0N/A * identically to {@link #EnumMap(EnumMap)}. Otherwise, the specified map
0N/A * must contain at least one mapping (in order to determine the new
0N/A * enum map's key type).
0N/A *
0N/A * @param m the map from which to initialize this enum map
0N/A * @throws IllegalArgumentException if <tt>m</tt> is not an
0N/A * <tt>EnumMap</tt> instance and contains no mappings
0N/A * @throws NullPointerException if <tt>m</tt> is null
0N/A */
0N/A public EnumMap(Map<K, ? extends V> m) {
0N/A if (m instanceof EnumMap) {
0N/A EnumMap<K, ? extends V> em = (EnumMap<K, ? extends V>) m;
0N/A keyType = em.keyType;
0N/A keyUniverse = em.keyUniverse;
0N/A vals = em.vals.clone();
0N/A size = em.size;
0N/A } else {
0N/A if (m.isEmpty())
0N/A throw new IllegalArgumentException("Specified map is empty");
0N/A keyType = m.keySet().iterator().next().getDeclaringClass();
0N/A keyUniverse = getKeyUniverse(keyType);
0N/A vals = new Object[keyUniverse.length];
0N/A putAll(m);
0N/A }
0N/A }
113N/A
0N/A // Query Operations
342N/A
342N/A /**
342N/A * Returns the number of key-value mappings in this map.
0N/A *
0N/A * @return the number of key-value mappings in this map
0N/A */
0N/A public int size() {
0N/A return size;
0N/A }
0N/A
0N/A /**
0N/A * Returns <tt>true</tt> if this map maps one or more keys to the
0N/A * specified value.
0N/A *
0N/A * @param value the value whose presence in this map is to be tested
0N/A * @return <tt>true</tt> if this map maps one or more keys to this value
0N/A */
0N/A public boolean containsValue(Object value) {
0N/A value = maskNull(value);
0N/A
0N/A for (Object val : vals)
0N/A if (value.equals(val))
0N/A return true;
0N/A
0N/A return false;
0N/A }
0N/A
0N/A /**
0N/A * Returns <tt>true</tt> if this map contains a mapping for the specified
0N/A * key.
0N/A *
0N/A * @param key the key whose presence in this map is to be tested
0N/A * @return <tt>true</tt> if this map contains a mapping for the specified
0N/A * key
0N/A */
0N/A public boolean containsKey(Object key) {
0N/A return isValidKey(key) && vals[((Enum)key).ordinal()] != null;
0N/A }
0N/A
0N/A private boolean containsMapping(Object key, Object value) {
0N/A return isValidKey(key) &&
0N/A maskNull(value).equals(vals[((Enum)key).ordinal()]);
0N/A }
0N/A
0N/A /**
0N/A * Returns the value to which the specified key is mapped,
13N/A * or {@code null} if this map contains no mapping for the key.
13N/A *
13N/A * <p>More formally, if this map contains a mapping from a key
13N/A * {@code k} to a value {@code v} such that {@code (key == k)},
13N/A * then this method returns {@code v}; otherwise it returns
13N/A * {@code null}. (There can be at most one such mapping.)
13N/A *
13N/A * <p>A return value of {@code null} does not <i>necessarily</i>
13N/A * indicate that the map contains no mapping for the key; it's also
13N/A * possible that the map explicitly maps the key to {@code null}.
13N/A * The {@link #containsKey containsKey} operation may be used to
13N/A * distinguish these two cases.
0N/A */
0N/A public V get(Object key) {
0N/A return (isValidKey(key) ?
0N/A unmaskNull(vals[((Enum)key).ordinal()]) : null);
0N/A }
0N/A
0N/A // Modification Operations
0N/A
0N/A /**
0N/A * Associates the specified value with the specified key in this map.
0N/A * If the map previously contained a mapping for this key, the old
0N/A * value is replaced.
0N/A *
0N/A * @param key the key with which the specified value is to be associated
0N/A * @param value the value to be associated with the specified key
0N/A *
0N/A * @return the previous value associated with specified key, or
0N/A * <tt>null</tt> if there was no mapping for key. (A <tt>null</tt>
0N/A * return can also indicate that the map previously associated
0N/A * <tt>null</tt> with the specified key.)
0N/A * @throws NullPointerException if the specified key is null
0N/A */
0N/A public V put(K key, V value) {
0N/A typeCheck(key);
0N/A
0N/A int index = key.ordinal();
0N/A Object oldValue = vals[index];
0N/A vals[index] = maskNull(value);
0N/A if (oldValue == null)
0N/A size++;
0N/A return unmaskNull(oldValue);
0N/A }
0N/A
0N/A /**
0N/A * Removes the mapping for this key from this map if present.
0N/A *
0N/A * @param key the key whose mapping is to be removed from the map
0N/A * @return the previous value associated with specified key, or
0N/A * <tt>null</tt> if there was no entry for key. (A <tt>null</tt>
0N/A * return can also indicate that the map previously associated
0N/A * <tt>null</tt> with the specified key.)
0N/A */
0N/A public V remove(Object key) {
0N/A if (!isValidKey(key))
0N/A return null;
0N/A int index = ((Enum)key).ordinal();
0N/A Object oldValue = vals[index];
0N/A vals[index] = null;
0N/A if (oldValue != null)
0N/A size--;
0N/A return unmaskNull(oldValue);
0N/A }
0N/A
0N/A private boolean removeMapping(Object key, Object value) {
0N/A if (!isValidKey(key))
0N/A return false;
0N/A int index = ((Enum)key).ordinal();
0N/A if (maskNull(value).equals(vals[index])) {
0N/A vals[index] = null;
0N/A size--;
0N/A return true;
0N/A }
0N/A return false;
0N/A }
0N/A
0N/A /**
0N/A * Returns true if key is of the proper type to be a key in this
0N/A * enum map.
0N/A */
0N/A private boolean isValidKey(Object key) {
0N/A if (key == null)
0N/A return false;
0N/A
0N/A // Cheaper than instanceof Enum followed by getDeclaringClass
0N/A Class keyClass = key.getClass();
0N/A return keyClass == keyType || keyClass.getSuperclass() == keyType;
0N/A }
0N/A
0N/A // Bulk Operations
0N/A
0N/A /**
0N/A * Copies all of the mappings from the specified map to this map.
0N/A * These mappings will replace any mappings that this map had for
0N/A * any of the keys currently in the specified map.
0N/A *
0N/A * @param m the mappings to be stored in this map
0N/A * @throws NullPointerException the specified map is null, or if
0N/A * one or more keys in the specified map are null
0N/A */
0N/A public void putAll(Map<? extends K, ? extends V> m) {
0N/A if (m instanceof EnumMap) {
0N/A EnumMap<? extends K, ? extends V> em =
0N/A (EnumMap<? extends K, ? extends V>)m;
0N/A if (em.keyType != keyType) {
0N/A if (em.isEmpty())
0N/A return;
0N/A throw new ClassCastException(em.keyType + " != " + keyType);
0N/A }
0N/A
0N/A for (int i = 0; i < keyUniverse.length; i++) {
0N/A Object emValue = em.vals[i];
0N/A if (emValue != null) {
0N/A if (vals[i] == null)
0N/A size++;
0N/A vals[i] = emValue;
0N/A }
0N/A }
0N/A } else {
0N/A super.putAll(m);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Removes all mappings from this map.
0N/A */
0N/A public void clear() {
0N/A Arrays.fill(vals, null);
0N/A size = 0;
0N/A }
0N/A
0N/A // Views
0N/A
0N/A /**
0N/A * This field is initialized to contain an instance of the entry set
0N/A * view the first time this view is requested. The view is stateless,
0N/A * so there's no reason to create more than one.
0N/A */
0N/A private transient Set<Map.Entry<K,V>> entrySet = null;
0N/A
0N/A /**
0N/A * Returns a {@link Set} view of the keys contained in this map.
0N/A * The returned set obeys the general contract outlined in
0N/A * {@link Map#keySet()}. The set's iterator will return the keys
0N/A * in their natural order (the order in which the enum constants
0N/A * are declared).
0N/A *
0N/A * @return a set view of the keys contained in this enum map
0N/A */
0N/A public Set<K> keySet() {
0N/A Set<K> ks = keySet;
0N/A if (ks != null)
0N/A return ks;
0N/A else
0N/A return keySet = new KeySet();
0N/A }
0N/A
0N/A private class KeySet extends AbstractSet<K> {
0N/A public Iterator<K> iterator() {
0N/A return new KeyIterator();
0N/A }
0N/A public int size() {
0N/A return size;
0N/A }
0N/A public boolean contains(Object o) {
0N/A return containsKey(o);
0N/A }
0N/A public boolean remove(Object o) {
0N/A int oldSize = size;
0N/A EnumMap.this.remove(o);
0N/A return size != oldSize;
0N/A }
0N/A public void clear() {
0N/A EnumMap.this.clear();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns a {@link Collection} view of the values contained in this map.
0N/A * The returned collection obeys the general contract outlined in
0N/A * {@link Map#values()}. The collection's iterator will return the
0N/A * values in the order their corresponding keys appear in map,
0N/A * which is their natural order (the order in which the enum constants
0N/A * are declared).
0N/A *
0N/A * @return a collection view of the values contained in this map
0N/A */
0N/A public Collection<V> values() {
0N/A Collection<V> vs = values;
0N/A if (vs != null)
0N/A return vs;
0N/A else
0N/A return values = new Values();
0N/A }
0N/A
0N/A private class Values extends AbstractCollection<V> {
0N/A public Iterator<V> iterator() {
0N/A return new ValueIterator();
0N/A }
0N/A public int size() {
0N/A return size;
0N/A }
0N/A public boolean contains(Object o) {
0N/A return containsValue(o);
0N/A }
0N/A public boolean remove(Object o) {
0N/A o = maskNull(o);
0N/A
0N/A for (int i = 0; i < vals.length; i++) {
0N/A if (o.equals(vals[i])) {
0N/A vals[i] = null;
0N/A size--;
0N/A return true;
0N/A }
0N/A }
0N/A return false;
0N/A }
0N/A public void clear() {
0N/A EnumMap.this.clear();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns a {@link Set} view of the mappings contained in this map.
0N/A * The returned set obeys the general contract outlined in
0N/A * {@link Map#keySet()}. The set's iterator will return the
0N/A * mappings in the order their keys appear in map, which is their
0N/A * natural order (the order in which the enum constants are declared).
0N/A *
0N/A * @return a set view of the mappings contained in this enum map
0N/A */
0N/A public Set<Map.Entry<K,V>> entrySet() {
0N/A Set<Map.Entry<K,V>> es = entrySet;
if (es != null)
return es;
else
return entrySet = new EntrySet();
}
private class EntrySet extends AbstractSet<Map.Entry<K,V>> {
public Iterator<Map.Entry<K,V>> iterator() {
return new EntryIterator();
}
public boolean contains(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry entry = (Map.Entry)o;
return containsMapping(entry.getKey(), entry.getValue());
}
public boolean remove(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry entry = (Map.Entry)o;
return removeMapping(entry.getKey(), entry.getValue());
}
public int size() {
return size;
}
public void clear() {
EnumMap.this.clear();
}
public Object[] toArray() {
return fillEntryArray(new Object[size]);
}
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
int size = size();
if (a.length < size)
a = (T[])java.lang.reflect.Array
.newInstance(a.getClass().getComponentType(), size);
if (a.length > size)
a[size] = null;
return (T[]) fillEntryArray(a);
}
private Object[] fillEntryArray(Object[] a) {
int j = 0;
for (int i = 0; i < vals.length; i++)
if (vals[i] != null)
a[j++] = new AbstractMap.SimpleEntry<>(
keyUniverse[i], unmaskNull(vals[i]));
return a;
}
}
private abstract class EnumMapIterator<T> implements Iterator<T> {
// Lower bound on index of next element to return
int index = 0;
// Index of last returned element, or -1 if none
int lastReturnedIndex = -1;
public boolean hasNext() {
while (index < vals.length && vals[index] == null)
index++;
return index != vals.length;
}
public void remove() {
checkLastReturnedIndex();
if (vals[lastReturnedIndex] != null) {
vals[lastReturnedIndex] = null;
size--;
}
lastReturnedIndex = -1;
}
private void checkLastReturnedIndex() {
if (lastReturnedIndex < 0)
throw new IllegalStateException();
}
}
private class KeyIterator extends EnumMapIterator<K> {
public K next() {
if (!hasNext())
throw new NoSuchElementException();
lastReturnedIndex = index++;
return keyUniverse[lastReturnedIndex];
}
}
private class ValueIterator extends EnumMapIterator<V> {
public V next() {
if (!hasNext())
throw new NoSuchElementException();
lastReturnedIndex = index++;
return unmaskNull(vals[lastReturnedIndex]);
}
}
/**
* Since we don't use Entry objects, we use the Iterator itself as entry.
*/
private class EntryIterator extends EnumMapIterator<Map.Entry<K,V>>
implements Map.Entry<K,V>
{
public Map.Entry<K,V> next() {
if (!hasNext())
throw new NoSuchElementException();
lastReturnedIndex = index++;
return this;
}
public K getKey() {
checkLastReturnedIndexForEntryUse();
return keyUniverse[lastReturnedIndex];
}
public V getValue() {
checkLastReturnedIndexForEntryUse();
return unmaskNull(vals[lastReturnedIndex]);
}
public V setValue(V value) {
checkLastReturnedIndexForEntryUse();
V oldValue = unmaskNull(vals[lastReturnedIndex]);
vals[lastReturnedIndex] = maskNull(value);
return oldValue;
}
public boolean equals(Object o) {
if (lastReturnedIndex < 0)
return o == this;
if (!(o instanceof Map.Entry))
return false;
Map.Entry e = (Map.Entry)o;
V ourValue = unmaskNull(vals[lastReturnedIndex]);
Object hisValue = e.getValue();
return e.getKey() == keyUniverse[lastReturnedIndex] &&
(ourValue == hisValue ||
(ourValue != null && ourValue.equals(hisValue)));
}
public int hashCode() {
if (lastReturnedIndex < 0)
return super.hashCode();
Object value = vals[lastReturnedIndex];
return keyUniverse[lastReturnedIndex].hashCode()
^ (value == NULL ? 0 : value.hashCode());
}
public String toString() {
if (lastReturnedIndex < 0)
return super.toString();
return keyUniverse[lastReturnedIndex] + "="
+ unmaskNull(vals[lastReturnedIndex]);
}
private void checkLastReturnedIndexForEntryUse() {
if (lastReturnedIndex < 0)
throw new IllegalStateException("Entry was removed");
}
}
// Comparison and hashing
/**
* Compares the specified object with this map for equality. Returns
* <tt>true</tt> if the given object is also a map and the two maps
* represent the same mappings, as specified in the {@link
* Map#equals(Object)} contract.
*
* @param o the object to be compared for equality with this map
* @return <tt>true</tt> if the specified object is equal to this map
*/
public boolean equals(Object o) {
if (!(o instanceof EnumMap))
return super.equals(o);
EnumMap em = (EnumMap)o;
if (em.keyType != keyType)
return size == 0 && em.size == 0;
// Key types match, compare each value
for (int i = 0; i < keyUniverse.length; i++) {
Object ourValue = vals[i];
Object hisValue = em.vals[i];
if (hisValue != ourValue &&
(hisValue == null || !hisValue.equals(ourValue)))
return false;
}
return true;
}
/**
* Returns a shallow copy of this enum map. (The values themselves
* are not cloned.
*
* @return a shallow copy of this enum map
*/
public EnumMap<K, V> clone() {
EnumMap<K, V> result = null;
try {
result = (EnumMap<K, V>) super.clone();
} catch(CloneNotSupportedException e) {
throw new AssertionError();
}
result.vals = result.vals.clone();
return result;
}
/**
* Throws an exception if e is not of the correct type for this enum set.
*/
private void typeCheck(K key) {
Class keyClass = key.getClass();
if (keyClass != keyType && keyClass.getSuperclass() != keyType)
throw new ClassCastException(keyClass + " != " + keyType);
}
/**
* Returns all of the values comprising K.
* The result is uncloned, cached, and shared by all callers.
*/
private static <K extends Enum<K>> K[] getKeyUniverse(Class<K> keyType) {
return SharedSecrets.getJavaLangAccess()
.getEnumConstantsShared(keyType);
}
private static final long serialVersionUID = 458661240069192865L;
/**
* Save the state of the <tt>EnumMap</tt> instance to a stream (i.e.,
* serialize it).
*
* @serialData The <i>size</i> of the enum map (the number of key-value
* mappings) is emitted (int), followed by the key (Object)
* and value (Object) for each key-value mapping represented
* by the enum map.
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException
{
// Write out the key type and any hidden stuff
s.defaultWriteObject();
// Write out size (number of Mappings)
s.writeInt(size);
// Write out keys and values (alternating)
for (Map.Entry<K,V> e : entrySet()) {
s.writeObject(e.getKey());
s.writeObject(e.getValue());
}
}
/**
* Reconstitute the <tt>EnumMap</tt> instance from a stream (i.e.,
* deserialize it).
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException
{
// Read in the key type and any hidden stuff
s.defaultReadObject();
keyUniverse = getKeyUniverse(keyType);
vals = new Object[keyUniverse.length];
// Read in size (number of Mappings)
int size = s.readInt();
// Read the keys and values, and put the mappings in the HashMap
for (int i = 0; i < size; i++) {
K key = (K) s.readObject();
V value = (V) s.readObject();
put(key, value);
}
}
}