• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  * Copyright (c) 2003, 2022, Oracle and/or its affiliates. All rights reserved.
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This code is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License version 2 only, as
8  * published by the Free Software Foundation.  Oracle designates this
9  * particular file as subject to the "Classpath" exception as provided
10  * by Oracle in the LICENSE file that accompanied this code.
11  *
12  * This code is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15  * version 2 for more details (a copy is included in the LICENSE file that
16  * accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License version
19  * 2 along with this work; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21  *
22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23  * or visit www.oracle.com if you need additional information or have any
24  * questions.
25  */
26 
27 package java.util;
28 
29 import jdk.internal.access.SharedSecrets;
30 
31 /**
32  * A specialized {@link Map} implementation for use with enum type keys.  All
33  * of the keys in an enum map must come from a single enum type that is
34  * specified, explicitly or implicitly, when the map is created.  Enum maps
35  * are represented internally as arrays.  This representation is extremely
36  * compact and efficient.
37  *
38  * <p>Enum maps are maintained in the <i>natural order</i> of their keys
39  * (the order in which the enum constants are declared).  This is reflected
40  * in the iterators returned by the collections views ({@link #keySet()},
41  * {@link #entrySet()}, and {@link #values()}).
42  *
43  * <p>Iterators returned by the collection views are <i>weakly consistent</i>:
44  * they will never throw {@link ConcurrentModificationException} and they may
45  * or may not show the effects of any modifications to the map that occur while
46  * the iteration is in progress.
47  *
48  * <p>Null keys are not permitted.  Attempts to insert a null key will
49  * throw {@link NullPointerException}.  Attempts to test for the
50  * presence of a null key or to remove one will, however, function properly.
51  * Null values are permitted.
52  *
53  * <P>Like most collection implementations {@code EnumMap} is not
54  * synchronized. If multiple threads access an enum map concurrently, and at
55  * least one of the threads modifies the map, it should be synchronized
56  * externally.  This is typically accomplished by synchronizing on some
57  * object that naturally encapsulates the enum map.  If no such object exists,
58  * the map should be "wrapped" using the {@link Collections#synchronizedMap}
59  * method.  This is best done at creation time, to prevent accidental
60  * unsynchronized access:
61  *
62  * <pre>
63  *     Map&lt;EnumKey, V&gt; m
64  *         = Collections.synchronizedMap(new EnumMap&lt;EnumKey, V&gt;(...));
65  * </pre>
66  *
67  * <p>Implementation note: All basic operations execute in constant time.
68  * They are likely (though not guaranteed) to be faster than their
69  * {@link HashMap} counterparts.
70  *
71  * <p>This class is a member of the
72  * <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
73  * Java Collections Framework</a>.
74  *
75  * @param <K> the enum type of keys maintained by this map
76  * @param <V> the type of mapped values
77  *
78  * @author Josh Bloch
79  * @see EnumSet
80  * @since 1.5
81  */
82 public class EnumMap<K extends Enum<K>, V> extends AbstractMap<K, V>
83     implements java.io.Serializable, Cloneable
84 {
85     /**
86      * The {@code Class} object for the enum type of all the keys of this map.
87      *
88      * @serial
89      */
90     private final Class<K> keyType;
91 
92     /**
93      * All of the values comprising K.  (Cached for performance.)
94      */
95     private transient K[] keyUniverse;
96 
97     /**
98      * Array representation of this map.  The ith element is the value
99      * to which universe[i] is currently mapped, or null if it isn't
100      * mapped to anything, or NULL if it's mapped to null.
101      */
102     private transient Object[] vals;
103 
104     /**
105      * The number of mappings in this map.
106      */
107     private transient int size = 0;
108 
109     /**
110      * Distinguished non-null value for representing null values.
111      */
112     private static final Object NULL = new Object() {
113         public int hashCode() {
114             return 0;
115         }
116 
117         public String toString() {
118             return "java.util.EnumMap.NULL";
119         }
120     };
121 
maskNull(Object value)122     private Object maskNull(Object value) {
123         return (value == null ? NULL : value);
124     }
125 
126     @SuppressWarnings("unchecked")
unmaskNull(Object value)127     private V unmaskNull(Object value) {
128         return (V)(value == NULL ? null : value);
129     }
130 
131     /**
132      * Creates an empty enum map with the specified key type.
133      *
134      * @param keyType the class object of the key type for this enum map
135      * @throws NullPointerException if {@code keyType} is null
136      */
EnumMap(Class<K> keyType)137     public EnumMap(Class<K> keyType) {
138         this.keyType = keyType;
139         keyUniverse = getKeyUniverse(keyType);
140         vals = new Object[keyUniverse.length];
141     }
142 
143     /**
144      * Creates an enum map with the same key type as the specified enum
145      * map, initially containing the same mappings (if any).
146      *
147      * @param m the enum map from which to initialize this enum map
148      * @throws NullPointerException if {@code m} is null
149      */
EnumMap(EnumMap<K, ? extends V> m)150     public EnumMap(EnumMap<K, ? extends V> m) {
151         keyType = m.keyType;
152         keyUniverse = m.keyUniverse;
153         vals = m.vals.clone();
154         size = m.size;
155     }
156 
157     /**
158      * Creates an enum map initialized from the specified map.  If the
159      * specified map is an {@code EnumMap} instance, this constructor behaves
160      * identically to {@link #EnumMap(EnumMap)}.  Otherwise, the specified map
161      * must contain at least one mapping (in order to determine the new
162      * enum map's key type).
163      *
164      * @param m the map from which to initialize this enum map
165      * @throws IllegalArgumentException if {@code m} is not an
166      *     {@code EnumMap} instance and contains no mappings
167      * @throws NullPointerException if {@code m} is null
168      */
EnumMap(Map<K, ? extends V> m)169     public EnumMap(Map<K, ? extends V> m) {
170         if (m instanceof EnumMap) {
171             EnumMap<K, ? extends V> em = (EnumMap<K, ? extends V>) m;
172             keyType = em.keyType;
173             keyUniverse = em.keyUniverse;
174             vals = em.vals.clone();
175             size = em.size;
176         } else {
177             if (m.isEmpty())
178                 throw new IllegalArgumentException("Specified map is empty");
179             keyType = m.keySet().iterator().next().getDeclaringClass();
180             keyUniverse = getKeyUniverse(keyType);
181             vals = new Object[keyUniverse.length];
182             putAll(m);
183         }
184     }
185 
186     // Query Operations
187 
188     /**
189      * Returns the number of key-value mappings in this map.
190      *
191      * @return the number of key-value mappings in this map
192      */
size()193     public int size() {
194         return size;
195     }
196 
197     /**
198      * Returns {@code true} if this map maps one or more keys to the
199      * specified value.
200      *
201      * @param value the value whose presence in this map is to be tested
202      * @return {@code true} if this map maps one or more keys to this value
203      */
containsValue(Object value)204     public boolean containsValue(Object value) {
205         value = maskNull(value);
206 
207         for (Object val : vals)
208             if (value.equals(val))
209                 return true;
210 
211         return false;
212     }
213 
214     /**
215      * Returns {@code true} if this map contains a mapping for the specified
216      * key.
217      *
218      * @param key the key whose presence in this map is to be tested
219      * @return {@code true} if this map contains a mapping for the specified
220      *            key
221      */
containsKey(Object key)222     public boolean containsKey(Object key) {
223         return isValidKey(key) && vals[((Enum<?>)key).ordinal()] != null;
224     }
225 
containsMapping(Object key, Object value)226     private boolean containsMapping(Object key, Object value) {
227         return isValidKey(key) &&
228             maskNull(value).equals(vals[((Enum<?>)key).ordinal()]);
229     }
230 
231     /**
232      * Returns the value to which the specified key is mapped,
233      * or {@code null} if this map contains no mapping for the key.
234      *
235      * <p>More formally, if this map contains a mapping from a key
236      * {@code k} to a value {@code v} such that {@code (key == k)},
237      * then this method returns {@code v}; otherwise it returns
238      * {@code null}.  (There can be at most one such mapping.)
239      *
240      * <p>A return value of {@code null} does not <i>necessarily</i>
241      * indicate that the map contains no mapping for the key; it's also
242      * possible that the map explicitly maps the key to {@code null}.
243      * The {@link #containsKey containsKey} operation may be used to
244      * distinguish these two cases.
245      */
get(Object key)246     public V get(Object key) {
247         return (isValidKey(key) ?
248                 unmaskNull(vals[((Enum<?>)key).ordinal()]) : null);
249     }
250 
251     // Modification Operations
252 
253     /**
254      * Associates the specified value with the specified key in this map.
255      * If the map previously contained a mapping for this key, the old
256      * value is replaced.
257      *
258      * @param key the key with which the specified value is to be associated
259      * @param value the value to be associated with the specified key
260      *
261      * @return the previous value associated with specified key, or
262      *     {@code null} if there was no mapping for key.  (A {@code null}
263      *     return can also indicate that the map previously associated
264      *     {@code null} with the specified key.)
265      * @throws NullPointerException if the specified key is null
266      */
put(K key, V value)267     public V put(K key, V value) {
268         typeCheck(key);
269 
270         int index = key.ordinal();
271         Object oldValue = vals[index];
272         vals[index] = maskNull(value);
273         if (oldValue == null)
274             size++;
275         return unmaskNull(oldValue);
276     }
277 
278     /**
279      * Removes the mapping for this key from this map if present.
280      *
281      * @param key the key whose mapping is to be removed from the map
282      * @return the previous value associated with specified key, or
283      *     {@code null} if there was no entry for key.  (A {@code null}
284      *     return can also indicate that the map previously associated
285      *     {@code null} with the specified key.)
286      */
remove(Object key)287     public V remove(Object key) {
288         if (!isValidKey(key))
289             return null;
290         int index = ((Enum<?>)key).ordinal();
291         Object oldValue = vals[index];
292         vals[index] = null;
293         if (oldValue != null)
294             size--;
295         return unmaskNull(oldValue);
296     }
297 
removeMapping(Object key, Object value)298     private boolean removeMapping(Object key, Object value) {
299         if (!isValidKey(key))
300             return false;
301         int index = ((Enum<?>)key).ordinal();
302         if (maskNull(value).equals(vals[index])) {
303             vals[index] = null;
304             size--;
305             return true;
306         }
307         return false;
308     }
309 
310     /**
311      * Returns true if key is of the proper type to be a key in this
312      * enum map.
313      */
isValidKey(Object key)314     private boolean isValidKey(Object key) {
315         if (key == null)
316             return false;
317 
318         // Cheaper than instanceof Enum followed by getDeclaringClass
319         Class<?> keyClass = key.getClass();
320         return keyClass == keyType || keyClass.getSuperclass() == keyType;
321     }
322 
323     // Bulk Operations
324 
325     /**
326      * Copies all of the mappings from the specified map to this map.
327      * These mappings will replace any mappings that this map had for
328      * any of the keys currently in the specified map.
329      *
330      * @param m the mappings to be stored in this map
331      * @throws NullPointerException the specified map is null, or if
332      *     one or more keys in the specified map are null
333      */
putAll(Map<? extends K, ? extends V> m)334     public void putAll(Map<? extends K, ? extends V> m) {
335         if (m instanceof EnumMap<?, ?> em) {
336             if (em.keyType != keyType) {
337                 if (em.isEmpty())
338                     return;
339                 throw new ClassCastException(em.keyType + " != " + keyType);
340             }
341 
342             for (int i = 0; i < keyUniverse.length; i++) {
343                 Object emValue = em.vals[i];
344                 if (emValue != null) {
345                     if (vals[i] == null)
346                         size++;
347                     vals[i] = emValue;
348                 }
349             }
350         } else {
351             super.putAll(m);
352         }
353     }
354 
355     /**
356      * Removes all mappings from this map.
357      */
clear()358     public void clear() {
359         Arrays.fill(vals, null);
360         size = 0;
361     }
362 
363     // Views
364 
365     /**
366      * This field is initialized to contain an instance of the entry set
367      * view the first time this view is requested.  The view is stateless,
368      * so there's no reason to create more than one.
369      */
370     private transient Set<Map.Entry<K,V>> entrySet;
371 
372     /**
373      * Returns a {@link Set} view of the keys contained in this map.
374      * The returned set obeys the general contract outlined in
375      * {@link Map#keySet()}.  The set's iterator will return the keys
376      * in their natural order (the order in which the enum constants
377      * are declared).
378      *
379      * @return a set view of the keys contained in this enum map
380      */
keySet()381     public Set<K> keySet() {
382         Set<K> ks = keySet;
383         if (ks == null) {
384             ks = new KeySet();
385             keySet = ks;
386         }
387         return ks;
388     }
389 
390     private class KeySet extends AbstractSet<K> {
iterator()391         public Iterator<K> iterator() {
392             return new KeyIterator();
393         }
size()394         public int size() {
395             return size;
396         }
contains(Object o)397         public boolean contains(Object o) {
398             return containsKey(o);
399         }
remove(Object o)400         public boolean remove(Object o) {
401             int oldSize = size;
402             EnumMap.this.remove(o);
403             return size != oldSize;
404         }
clear()405         public void clear() {
406             EnumMap.this.clear();
407         }
408     }
409 
410     /**
411      * Returns a {@link Collection} view of the values contained in this map.
412      * The returned collection obeys the general contract outlined in
413      * {@link Map#values()}.  The collection's iterator will return the
414      * values in the order their corresponding keys appear in map,
415      * which is their natural order (the order in which the enum constants
416      * are declared).
417      *
418      * @return a collection view of the values contained in this map
419      */
values()420     public Collection<V> values() {
421         Collection<V> vs = values;
422         if (vs == null) {
423             vs = new Values();
424             values = vs;
425         }
426         return vs;
427     }
428 
429     private class Values extends AbstractCollection<V> {
iterator()430         public Iterator<V> iterator() {
431             return new ValueIterator();
432         }
size()433         public int size() {
434             return size;
435         }
contains(Object o)436         public boolean contains(Object o) {
437             return containsValue(o);
438         }
remove(Object o)439         public boolean remove(Object o) {
440             o = maskNull(o);
441 
442             for (int i = 0; i < vals.length; i++) {
443                 if (o.equals(vals[i])) {
444                     vals[i] = null;
445                     size--;
446                     return true;
447                 }
448             }
449             return false;
450         }
clear()451         public void clear() {
452             EnumMap.this.clear();
453         }
454     }
455 
456     /**
457      * Returns a {@link Set} view of the mappings contained in this map.
458      * The returned set obeys the general contract outlined in
459      * {@link Map#keySet()}.  The set's iterator will return the
460      * mappings in the order their keys appear in map, which is their
461      * natural order (the order in which the enum constants are declared).
462      *
463      * @return a set view of the mappings contained in this enum map
464      */
entrySet()465     public Set<Map.Entry<K,V>> entrySet() {
466         Set<Map.Entry<K,V>> es = entrySet;
467         if (es != null)
468             return es;
469         else
470             return entrySet = new EntrySet();
471     }
472 
473     private class EntrySet extends AbstractSet<Map.Entry<K,V>> {
iterator()474         public Iterator<Map.Entry<K,V>> iterator() {
475             return new EntryIterator();
476         }
477 
contains(Object o)478         public boolean contains(Object o) {
479             return o instanceof Map.Entry<?, ?> entry
480                     && containsMapping(entry.getKey(), entry.getValue());
481         }
remove(Object o)482         public boolean remove(Object o) {
483             return o instanceof Map.Entry<?, ?> entry
484                     && removeMapping(entry.getKey(), entry.getValue());
485         }
size()486         public int size() {
487             return size;
488         }
clear()489         public void clear() {
490             EnumMap.this.clear();
491         }
toArray()492         public Object[] toArray() {
493             return fillEntryArray(new Object[size]);
494         }
495         @SuppressWarnings("unchecked")
toArray(T[] a)496         public <T> T[] toArray(T[] a) {
497             int size = size();
498             if (a.length < size)
499                 a = (T[])java.lang.reflect.Array
500                     .newInstance(a.getClass().getComponentType(), size);
501             if (a.length > size)
502                 a[size] = null;
503             return (T[]) fillEntryArray(a);
504         }
fillEntryArray(Object[] a)505         private Object[] fillEntryArray(Object[] a) {
506             int j = 0;
507             for (int i = 0; i < vals.length; i++)
508                 if (vals[i] != null)
509                     a[j++] = new AbstractMap.SimpleEntry<>(
510                         keyUniverse[i], unmaskNull(vals[i]));
511             return a;
512         }
513     }
514 
515     private abstract class EnumMapIterator<T> implements Iterator<T> {
516         // Lower bound on index of next element to return
517         int index = 0;
518 
519         // Index of last returned element, or -1 if none
520         int lastReturnedIndex = -1;
521 
hasNext()522         public boolean hasNext() {
523             while (index < vals.length && vals[index] == null)
524                 index++;
525             return index != vals.length;
526         }
527 
remove()528         public void remove() {
529             checkLastReturnedIndex();
530 
531             if (vals[lastReturnedIndex] != null) {
532                 vals[lastReturnedIndex] = null;
533                 size--;
534             }
535             lastReturnedIndex = -1;
536         }
537 
checkLastReturnedIndex()538         private void checkLastReturnedIndex() {
539             if (lastReturnedIndex < 0)
540                 throw new IllegalStateException();
541         }
542     }
543 
544     private class KeyIterator extends EnumMapIterator<K> {
next()545         public K next() {
546             if (!hasNext())
547                 throw new NoSuchElementException();
548             lastReturnedIndex = index++;
549             return keyUniverse[lastReturnedIndex];
550         }
551     }
552 
553     private class ValueIterator extends EnumMapIterator<V> {
next()554         public V next() {
555             if (!hasNext())
556                 throw new NoSuchElementException();
557             lastReturnedIndex = index++;
558             return unmaskNull(vals[lastReturnedIndex]);
559         }
560     }
561 
562     private class EntryIterator extends EnumMapIterator<Map.Entry<K,V>> {
563         private Entry lastReturnedEntry;
564 
next()565         public Map.Entry<K,V> next() {
566             if (!hasNext())
567                 throw new NoSuchElementException();
568             lastReturnedEntry = new Entry(index++);
569             return lastReturnedEntry;
570         }
571 
remove()572         public void remove() {
573             lastReturnedIndex =
574                 ((null == lastReturnedEntry) ? -1 : lastReturnedEntry.index);
575             super.remove();
576             lastReturnedEntry.index = lastReturnedIndex;
577             lastReturnedEntry = null;
578         }
579 
580         private class Entry implements Map.Entry<K,V> {
581             private int index;
582 
Entry(int index)583             private Entry(int index) {
584                 this.index = index;
585             }
586 
getKey()587             public K getKey() {
588                 checkIndexForEntryUse();
589                 return keyUniverse[index];
590             }
591 
getValue()592             public V getValue() {
593                 checkIndexForEntryUse();
594                 return unmaskNull(vals[index]);
595             }
596 
setValue(V value)597             public V setValue(V value) {
598                 checkIndexForEntryUse();
599                 V oldValue = unmaskNull(vals[index]);
600                 vals[index] = maskNull(value);
601                 return oldValue;
602             }
603 
equals(Object o)604             public boolean equals(Object o) {
605                 if (index < 0)
606                     return o == this;
607 
608                 if (!(o instanceof Map.Entry<?, ?> e))
609                     return false;
610 
611                 V ourValue = unmaskNull(vals[index]);
612                 Object hisValue = e.getValue();
613                 return (e.getKey() == keyUniverse[index] &&
614                         (ourValue == hisValue ||
615                          (ourValue != null && ourValue.equals(hisValue))));
616             }
617 
hashCode()618             public int hashCode() {
619                 if (index < 0)
620                     return super.hashCode();
621 
622                 return entryHashCode(index);
623             }
624 
toString()625             public String toString() {
626                 if (index < 0)
627                     return super.toString();
628 
629                 return keyUniverse[index] + "="
630                     + unmaskNull(vals[index]);
631             }
632 
checkIndexForEntryUse()633             private void checkIndexForEntryUse() {
634                 if (index < 0)
635                     throw new IllegalStateException("Entry was removed");
636             }
637         }
638     }
639 
640     // Comparison and hashing
641 
642     /**
643      * Compares the specified object with this map for equality.  Returns
644      * {@code true} if the given object is also a map and the two maps
645      * represent the same mappings, as specified in the {@link
646      * Map#equals(Object)} contract.
647      *
648      * @param o the object to be compared for equality with this map
649      * @return {@code true} if the specified object is equal to this map
650      */
equals(Object o)651     public boolean equals(Object o) {
652         if (this == o)
653             return true;
654         if (o instanceof EnumMap)
655             return equals((EnumMap<?,?>)o);
656         if (!(o instanceof Map<?, ?> m))
657             return false;
658 
659         if (size != m.size())
660             return false;
661 
662         for (int i = 0; i < keyUniverse.length; i++) {
663             if (null != vals[i]) {
664                 K key = keyUniverse[i];
665                 V value = unmaskNull(vals[i]);
666                 if (null == value) {
667                     if (!((null == m.get(key)) && m.containsKey(key)))
668                        return false;
669                 } else {
670                    if (!value.equals(m.get(key)))
671                       return false;
672                 }
673             }
674         }
675 
676         return true;
677     }
678 
equals(EnumMap<?,?> em)679     private boolean equals(EnumMap<?,?> em) {
680         if (em.size != size)
681             return false;
682 
683         if (em.keyType != keyType)
684             return size == 0;
685 
686         // Key types match, compare each value
687         for (int i = 0; i < keyUniverse.length; i++) {
688             Object ourValue =    vals[i];
689             Object hisValue = em.vals[i];
690             if (hisValue != ourValue &&
691                 (hisValue == null || !hisValue.equals(ourValue)))
692                 return false;
693         }
694         return true;
695     }
696 
697     /**
698      * Returns the hash code value for this map.  The hash code of a map is
699      * defined to be the sum of the hash codes of each entry in the map.
700      */
hashCode()701     public int hashCode() {
702         int h = 0;
703 
704         for (int i = 0; i < keyUniverse.length; i++) {
705             if (null != vals[i]) {
706                 h += entryHashCode(i);
707             }
708         }
709 
710         return h;
711     }
712 
entryHashCode(int index)713     private int entryHashCode(int index) {
714         return (keyUniverse[index].hashCode() ^ vals[index].hashCode());
715     }
716 
717     /**
718      * Returns a shallow copy of this enum map. The values themselves
719      * are not cloned.
720      *
721      * @return a shallow copy of this enum map
722      */
723     @SuppressWarnings("unchecked")
clone()724     public EnumMap<K, V> clone() {
725         EnumMap<K, V> result = null;
726         try {
727             result = (EnumMap<K, V>) super.clone();
728         } catch(CloneNotSupportedException e) {
729             throw new AssertionError();
730         }
731         result.vals = result.vals.clone();
732         result.entrySet = null;
733         return result;
734     }
735 
736     /**
737      * Throws an exception if e is not of the correct type for this enum set.
738      */
typeCheck(K key)739     private void typeCheck(K key) {
740         Class<?> keyClass = key.getClass();
741         if (keyClass != keyType && keyClass.getSuperclass() != keyType)
742             throw new ClassCastException(keyClass + " != " + keyType);
743     }
744 
745     /**
746      * Returns all of the values comprising K.
747      * The result is uncloned, cached, and shared by all callers.
748      */
getKeyUniverse(Class<K> keyType)749     private static <K extends Enum<K>> K[] getKeyUniverse(Class<K> keyType) {
750         // Android-changed: Use getEnumConstantsShared directly instead of going
751         // through SharedSecrets.
752         return keyType.getEnumConstantsShared();
753     }
754 
755     @java.io.Serial
756     private static final long serialVersionUID = 458661240069192865L;
757 
758     /**
759      * Save the state of the {@code EnumMap} instance to a stream (i.e.,
760      * serialize it).
761      *
762      * @serialData The <i>size</i> of the enum map (the number of key-value
763      *             mappings) is emitted (int), followed by the key (Object)
764      *             and value (Object) for each key-value mapping represented
765      *             by the enum map.
766      */
767     @java.io.Serial
writeObject(java.io.ObjectOutputStream s)768     private void writeObject(java.io.ObjectOutputStream s)
769         throws java.io.IOException
770     {
771         // Write out the key type and any hidden stuff
772         s.defaultWriteObject();
773 
774         // Write out size (number of Mappings)
775         s.writeInt(size);
776 
777         // Write out keys and values (alternating)
778         int entriesToBeWritten = size;
779         for (int i = 0; entriesToBeWritten > 0; i++) {
780             if (null != vals[i]) {
781                 s.writeObject(keyUniverse[i]);
782                 s.writeObject(unmaskNull(vals[i]));
783                 entriesToBeWritten--;
784             }
785         }
786     }
787 
788     /**
789      * Reconstitute the {@code EnumMap} instance from a stream (i.e.,
790      * deserialize it).
791      */
792     @SuppressWarnings("unchecked")
793     @java.io.Serial
readObject(java.io.ObjectInputStream s)794     private void readObject(java.io.ObjectInputStream s)
795         throws java.io.IOException, ClassNotFoundException
796     {
797         // Read in the key type and any hidden stuff
798         s.defaultReadObject();
799 
800         keyUniverse = getKeyUniverse(keyType);
801         vals = new Object[keyUniverse.length];
802 
803         // Read in size (number of Mappings)
804         int size = s.readInt();
805 
806         // Read the keys and values, and put the mappings in the HashMap
807         for (int i = 0; i < size; i++) {
808             K key = (K) s.readObject();
809             V value = (V) s.readObject();
810             put(key, value);
811         }
812     }
813 }
814