• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */
25 
26 package java.util;
27 import java.util.Map.Entry;
28 import java.util.function.Consumer;
29 import java.util.function.IntFunction;
30 import java.util.function.Predicate;
31 import java.util.stream.Stream;
32 
33 /**
34  * This class provides a skeletal implementation of the {@code Map}
35  * interface, to minimize the effort required to implement this interface.
36  *
37  * <p>To implement an unmodifiable map, the programmer needs only to extend this
38  * class and provide an implementation for the {@code entrySet} method, which
39  * returns a set-view of the map's mappings.  Typically, the returned set
40  * will, in turn, be implemented atop {@code AbstractSet}.  This set should
41  * not support the {@code add} or {@code remove} methods, and its iterator
42  * should not support the {@code remove} method.
43  *
44  * <p>To implement a modifiable map, the programmer must additionally override
45  * this class's {@code put} method (which otherwise throws an
46  * {@code UnsupportedOperationException}), and the iterator returned by
47  * {@code entrySet().iterator()} must additionally implement its
48  * {@code remove} method.
49  *
50  * <p>The programmer should generally provide a void (no argument) and map
51  * constructor, as per the recommendation in the {@code Map} interface
52  * specification.
53  *
54  * <p>The documentation for each non-abstract method in this class describes its
55  * implementation in detail.  Each of these methods may be overridden if the
56  * map being implemented admits a more efficient implementation.
57  *
58  * <p>This class is a member of the
59  * <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
60  * Java Collections Framework</a>.
61  *
62  * @param <K> the type of keys maintained by this map
63  * @param <V> the type of mapped values
64  *
65  * @author  Josh Bloch
66  * @author  Neal Gafter
67  * @see Map
68  * @see Collection
69  * @since 1.2
70  */
71 
72 public abstract class AbstractMap<K,V> implements Map<K,V> {
73     /**
74      * Sole constructor.  (For invocation by subclass constructors, typically
75      * implicit.)
76      */
AbstractMap()77     protected AbstractMap() {
78     }
79 
80     // Query Operations
81 
82     /**
83      * {@inheritDoc}
84      *
85      * @implSpec
86      * This implementation returns {@code entrySet().size()}.
87      */
size()88     public int size() {
89         return entrySet().size();
90     }
91 
92     /**
93      * {@inheritDoc}
94      *
95      * @implSpec
96      * This implementation returns {@code size() == 0}.
97      */
isEmpty()98     public boolean isEmpty() {
99         return size() == 0;
100     }
101 
102     /**
103      * {@inheritDoc}
104      *
105      * @implSpec
106      * This implementation iterates over {@code entrySet()} searching
107      * for an entry with the specified value.  If such an entry is found,
108      * {@code true} is returned.  If the iteration terminates without
109      * finding such an entry, {@code false} is returned.  Note that this
110      * implementation requires linear time in the size of the map.
111      *
112      * @throws ClassCastException   {@inheritDoc}
113      * @throws NullPointerException {@inheritDoc}
114      */
containsValue(Object value)115     public boolean containsValue(Object value) {
116         Iterator<Entry<K,V>> i = entrySet().iterator();
117         if (value==null) {
118             while (i.hasNext()) {
119                 Entry<K,V> e = i.next();
120                 if (e.getValue()==null)
121                     return true;
122             }
123         } else {
124             while (i.hasNext()) {
125                 Entry<K,V> e = i.next();
126                 if (value.equals(e.getValue()))
127                     return true;
128             }
129         }
130         return false;
131     }
132 
133     /**
134      * {@inheritDoc}
135      *
136      * @implSpec
137      * This implementation iterates over {@code entrySet()} searching
138      * for an entry with the specified key.  If such an entry is found,
139      * {@code true} is returned.  If the iteration terminates without
140      * finding such an entry, {@code false} is returned.  Note that this
141      * implementation requires linear time in the size of the map; many
142      * implementations will override this method.
143      *
144      * @throws ClassCastException   {@inheritDoc}
145      * @throws NullPointerException {@inheritDoc}
146      */
containsKey(Object key)147     public boolean containsKey(Object key) {
148         Iterator<Map.Entry<K,V>> i = entrySet().iterator();
149         if (key==null) {
150             while (i.hasNext()) {
151                 Entry<K,V> e = i.next();
152                 if (e.getKey()==null)
153                     return true;
154             }
155         } else {
156             while (i.hasNext()) {
157                 Entry<K,V> e = i.next();
158                 if (key.equals(e.getKey()))
159                     return true;
160             }
161         }
162         return false;
163     }
164 
165     /**
166      * {@inheritDoc}
167      *
168      * @implSpec
169      * This implementation iterates over {@code entrySet()} searching
170      * for an entry with the specified key.  If such an entry is found,
171      * the entry's value is returned.  If the iteration terminates without
172      * finding such an entry, {@code null} is returned.  Note that this
173      * implementation requires linear time in the size of the map; many
174      * implementations will override this method.
175      *
176      * @throws ClassCastException            {@inheritDoc}
177      * @throws NullPointerException          {@inheritDoc}
178      */
get(Object key)179     public V get(Object key) {
180         Iterator<Entry<K,V>> i = entrySet().iterator();
181         if (key==null) {
182             while (i.hasNext()) {
183                 Entry<K,V> e = i.next();
184                 if (e.getKey()==null)
185                     return e.getValue();
186             }
187         } else {
188             while (i.hasNext()) {
189                 Entry<K,V> e = i.next();
190                 if (key.equals(e.getKey()))
191                     return e.getValue();
192             }
193         }
194         return null;
195     }
196 
197 
198     // Modification Operations
199 
200     /**
201      * {@inheritDoc}
202      *
203      * @implSpec
204      * This implementation always throws an
205      * {@code UnsupportedOperationException}.
206      *
207      * @throws UnsupportedOperationException {@inheritDoc}
208      * @throws ClassCastException            {@inheritDoc}
209      * @throws NullPointerException          {@inheritDoc}
210      * @throws IllegalArgumentException      {@inheritDoc}
211      */
put(K key, V value)212     public V put(K key, V value) {
213         throw new UnsupportedOperationException();
214     }
215 
216     /**
217      * {@inheritDoc}
218      *
219      * @implSpec
220      * This implementation iterates over {@code entrySet()} searching for an
221      * entry with the specified key.  If such an entry is found, its value is
222      * obtained with its {@code getValue} operation, the entry is removed
223      * from the collection (and the backing map) with the iterator's
224      * {@code remove} operation, and the saved value is returned.  If the
225      * iteration terminates without finding such an entry, {@code null} is
226      * returned.  Note that this implementation requires linear time in the
227      * size of the map; many implementations will override this method.
228      *
229      * <p>Note that this implementation throws an
230      * {@code UnsupportedOperationException} if the {@code entrySet}
231      * iterator does not support the {@code remove} method and this map
232      * contains a mapping for the specified key.
233      *
234      * @throws UnsupportedOperationException {@inheritDoc}
235      * @throws ClassCastException            {@inheritDoc}
236      * @throws NullPointerException          {@inheritDoc}
237      */
remove(Object key)238     public V remove(Object key) {
239         Iterator<Entry<K,V>> i = entrySet().iterator();
240         Entry<K,V> correctEntry = null;
241         if (key==null) {
242             while (correctEntry==null && i.hasNext()) {
243                 Entry<K,V> e = i.next();
244                 if (e.getKey()==null)
245                     correctEntry = e;
246             }
247         } else {
248             while (correctEntry==null && i.hasNext()) {
249                 Entry<K,V> e = i.next();
250                 if (key.equals(e.getKey()))
251                     correctEntry = e;
252             }
253         }
254 
255         V oldValue = null;
256         if (correctEntry !=null) {
257             oldValue = correctEntry.getValue();
258             i.remove();
259         }
260         return oldValue;
261     }
262 
263 
264     // Bulk Operations
265 
266     /**
267      * {@inheritDoc}
268      *
269      * @implSpec
270      * This implementation iterates over the specified map's
271      * {@code entrySet()} collection, and calls this map's {@code put}
272      * operation once for each entry returned by the iteration.
273      *
274      * <p>Note that this implementation throws an
275      * {@code UnsupportedOperationException} if this map does not support
276      * the {@code put} operation and the specified map is nonempty.
277      *
278      * @throws UnsupportedOperationException {@inheritDoc}
279      * @throws ClassCastException            {@inheritDoc}
280      * @throws NullPointerException          {@inheritDoc}
281      * @throws IllegalArgumentException      {@inheritDoc}
282      */
putAll(Map<? extends K, ? extends V> m)283     public void putAll(Map<? extends K, ? extends V> m) {
284         for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
285             put(e.getKey(), e.getValue());
286     }
287 
288     /**
289      * {@inheritDoc}
290      *
291      * @implSpec
292      * This implementation calls {@code entrySet().clear()}.
293      *
294      * <p>Note that this implementation throws an
295      * {@code UnsupportedOperationException} if the {@code entrySet}
296      * does not support the {@code clear} operation.
297      *
298      * @throws UnsupportedOperationException {@inheritDoc}
299      */
clear()300     public void clear() {
301         entrySet().clear();
302     }
303 
304 
305     // Views
306 
307     /**
308      * Each of these fields are initialized to contain an instance of the
309      * appropriate view the first time this view is requested.  The views are
310      * stateless, so there's no reason to create more than one of each.
311      *
312      * <p>Since there is no synchronization performed while accessing these fields,
313      * it is expected that java.util.Map view classes using these fields have
314      * no non-final fields (or any fields at all except for outer-this). Adhering
315      * to this rule would make the races on these fields benign.
316      *
317      * <p>It is also imperative that implementations read the field only once,
318      * as in:
319      *
320      * <pre> {@code
321      * public Set<K> keySet() {
322      *   Set<K> ks = keySet;  // single racy read
323      *   if (ks == null) {
324      *     ks = new KeySet();
325      *     keySet = ks;
326      *   }
327      *   return ks;
328      * }
329      *}</pre>
330      */
331     transient Set<K>        keySet;
332     transient Collection<V> values;
333 
334     /**
335      * {@inheritDoc}
336      *
337      * @implSpec
338      * This implementation returns a set that subclasses {@link AbstractSet}.
339      * The subclass's iterator method returns a "wrapper object" over this
340      * map's {@code entrySet()} iterator.  The {@code size} method
341      * delegates to this map's {@code size} method and the
342      * {@code contains} method delegates to this map's
343      * {@code containsKey} method.
344      *
345      * <p>The set is created the first time this method is called,
346      * and returned in response to all subsequent calls.  No synchronization
347      * is performed, so there is a slight chance that multiple calls to this
348      * method will not all return the same set.
349      */
keySet()350     public Set<K> keySet() {
351         Set<K> ks = keySet;
352         if (ks == null) {
353             ks = new AbstractSet<K>() {
354                 public Iterator<K> iterator() {
355                     return new Iterator<K>() {
356                         private Iterator<Entry<K,V>> i = entrySet().iterator();
357 
358                         public boolean hasNext() {
359                             return i.hasNext();
360                         }
361 
362                         public K next() {
363                             return i.next().getKey();
364                         }
365 
366                         public void remove() {
367                             i.remove();
368                         }
369                     };
370                 }
371 
372                 public int size() {
373                     return AbstractMap.this.size();
374                 }
375 
376                 public boolean isEmpty() {
377                     return AbstractMap.this.isEmpty();
378                 }
379 
380                 public void clear() {
381                     AbstractMap.this.clear();
382                 }
383 
384                 public boolean contains(Object k) {
385                     return AbstractMap.this.containsKey(k);
386                 }
387             };
388             keySet = ks;
389         }
390         return ks;
391     }
392 
393     /**
394      * {@inheritDoc}
395      *
396      * @implSpec
397      * This implementation returns a collection that subclasses {@link
398      * AbstractCollection}.  The subclass's iterator method returns a
399      * "wrapper object" over this map's {@code entrySet()} iterator.
400      * The {@code size} method delegates to this map's {@code size}
401      * method and the {@code contains} method delegates to this map's
402      * {@code containsValue} method.
403      *
404      * <p>The collection is created the first time this method is called, and
405      * returned in response to all subsequent calls.  No synchronization is
406      * performed, so there is a slight chance that multiple calls to this
407      * method will not all return the same collection.
408      */
values()409     public Collection<V> values() {
410         Collection<V> vals = values;
411         if (vals == null) {
412             vals = new AbstractCollection<V>() {
413                 public Iterator<V> iterator() {
414                     return new Iterator<V>() {
415                         private Iterator<Entry<K,V>> i = entrySet().iterator();
416 
417                         public boolean hasNext() {
418                             return i.hasNext();
419                         }
420 
421                         public V next() {
422                             return i.next().getValue();
423                         }
424 
425                         public void remove() {
426                             i.remove();
427                         }
428                     };
429                 }
430 
431                 public int size() {
432                     return AbstractMap.this.size();
433                 }
434 
435                 public boolean isEmpty() {
436                     return AbstractMap.this.isEmpty();
437                 }
438 
439                 public void clear() {
440                     AbstractMap.this.clear();
441                 }
442 
443                 public boolean contains(Object v) {
444                     return AbstractMap.this.containsValue(v);
445                 }
446             };
447             values = vals;
448         }
449         return vals;
450     }
451 
entrySet()452     public abstract Set<Entry<K,V>> entrySet();
453 
454 
455     // Comparison and hashing
456 
457     /**
458      * Compares the specified object with this map for equality.  Returns
459      * {@code true} if the given object is also a map and the two maps
460      * represent the same mappings.  More formally, two maps {@code m1} and
461      * {@code m2} represent the same mappings if
462      * {@code m1.entrySet().equals(m2.entrySet())}.  This ensures that the
463      * {@code equals} method works properly across different implementations
464      * of the {@code Map} interface.
465      *
466      * @implSpec
467      * This implementation first checks if the specified object is this map;
468      * if so it returns {@code true}.  Then, it checks if the specified
469      * object is a map whose size is identical to the size of this map; if
470      * not, it returns {@code false}.  If so, it iterates over this map's
471      * {@code entrySet} collection, and checks that the specified map
472      * contains each mapping that this map contains.  If the specified map
473      * fails to contain such a mapping, {@code false} is returned.  If the
474      * iteration completes, {@code true} is returned.
475      *
476      * @param o object to be compared for equality with this map
477      * @return {@code true} if the specified object is equal to this map
478      */
equals(Object o)479     public boolean equals(Object o) {
480         if (o == this)
481             return true;
482 
483         if (!(o instanceof Map<?, ?> m))
484             return false;
485         if (m.size() != size())
486             return false;
487 
488         try {
489             for (Entry<K, V> e : entrySet()) {
490                 K key = e.getKey();
491                 V value = e.getValue();
492                 if (value == null) {
493                     if (!(m.get(key) == null && m.containsKey(key)))
494                         return false;
495                 } else {
496                     if (!value.equals(m.get(key)))
497                         return false;
498                 }
499             }
500         } catch (ClassCastException | NullPointerException unused) {
501             return false;
502         }
503 
504         return true;
505     }
506 
507     /**
508      * Returns the hash code value for this map.  The hash code of a map is
509      * defined to be the sum of the hash codes of each entry in the map's
510      * {@code entrySet()} view.  This ensures that {@code m1.equals(m2)}
511      * implies that {@code m1.hashCode()==m2.hashCode()} for any two maps
512      * {@code m1} and {@code m2}, as required by the general contract of
513      * {@link Object#hashCode}.
514      *
515      * @implSpec
516      * This implementation iterates over {@code entrySet()}, calling
517      * {@link Map.Entry#hashCode hashCode()} on each element (entry) in the
518      * set, and adding up the results.
519      *
520      * @return the hash code value for this map
521      * @see Map.Entry#hashCode()
522      * @see Object#equals(Object)
523      * @see Set#equals(Object)
524      */
hashCode()525     public int hashCode() {
526         int h = 0;
527         for (Entry<K, V> entry : entrySet())
528             h += entry.hashCode();
529         return h;
530     }
531 
532     /**
533      * Returns a string representation of this map.  The string representation
534      * consists of a list of key-value mappings in the order returned by the
535      * map's {@code entrySet} view's iterator, enclosed in braces
536      * ({@code "{}"}).  Adjacent mappings are separated by the characters
537      * {@code ", "} (comma and space).  Each key-value mapping is rendered as
538      * the key followed by an equals sign ({@code "="}) followed by the
539      * associated value.  Keys and values are converted to strings as by
540      * {@link String#valueOf(Object)}.
541      *
542      * @return a string representation of this map
543      */
toString()544     public String toString() {
545         Iterator<Entry<K,V>> i = entrySet().iterator();
546         if (! i.hasNext())
547             return "{}";
548 
549         StringBuilder sb = new StringBuilder();
550         sb.append('{');
551         for (;;) {
552             Entry<K,V> e = i.next();
553             K key = e.getKey();
554             V value = e.getValue();
555             sb.append(key   == this ? "(this Map)" : key);
556             sb.append('=');
557             sb.append(value == this ? "(this Map)" : value);
558             if (! i.hasNext())
559                 return sb.append('}').toString();
560             sb.append(',').append(' ');
561         }
562     }
563 
564     /**
565      * Returns a shallow copy of this {@code AbstractMap} instance: the keys
566      * and values themselves are not cloned.
567      *
568      * @return a shallow copy of this map
569      */
clone()570     protected Object clone() throws CloneNotSupportedException {
571         AbstractMap<?,?> result = (AbstractMap<?,?>)super.clone();
572         result.keySet = null;
573         result.values = null;
574         return result;
575     }
576 
577     /**
578      * Utility method for SimpleEntry and SimpleImmutableEntry.
579      * Test for equality, checking for nulls.
580      *
581      * NB: Do not replace with Object.equals until JDK-8015417 is resolved.
582      */
eq(Object o1, Object o2)583     private static boolean eq(Object o1, Object o2) {
584         return o1 == null ? o2 == null : o1.equals(o2);
585     }
586 
587     // Implementation Note: SimpleEntry and SimpleImmutableEntry
588     // are distinct unrelated classes, even though they share
589     // some code. Since you can't add or subtract final-ness
590     // of a field in a subclass, they can't share representations,
591     // and the amount of duplicated code is too small to warrant
592     // exposing a common abstract class.
593 
594 
595     /**
596      * An Entry maintaining a key and a value.  The value may be
597      * changed using the {@code setValue} method. Instances of
598      * this class are not associated with any map nor with any
599      * map's entry-set view.
600      *
601      * @apiNote
602      * This class facilitates the process of building custom map
603      * implementations. For example, it may be convenient to return
604      * arrays of {@code SimpleEntry} instances in method
605      * {@code Map.entrySet().toArray}.
606      *
607      * @param <K> the type of key
608      * @param <V> the type of the value
609      *
610      * @since 1.6
611      */
612     public static class SimpleEntry<K,V>
613         implements Entry<K,V>, java.io.Serializable
614     {
615         @java.io.Serial
616         private static final long serialVersionUID = -8499721149061103585L;
617 
618         @SuppressWarnings("serial") // Conditionally serializable
619         private final K key;
620         @SuppressWarnings("serial") // Conditionally serializable
621         private V value;
622 
623         /**
624          * Creates an entry representing a mapping from the specified
625          * key to the specified value.
626          *
627          * @param key the key represented by this entry
628          * @param value the value represented by this entry
629          */
SimpleEntry(K key, V value)630         public SimpleEntry(K key, V value) {
631             this.key   = key;
632             this.value = value;
633         }
634 
635         /**
636          * Creates an entry representing the same mapping as the
637          * specified entry.
638          *
639          * @param entry the entry to copy
640          */
SimpleEntry(Entry<? extends K, ? extends V> entry)641         public SimpleEntry(Entry<? extends K, ? extends V> entry) {
642             this.key   = entry.getKey();
643             this.value = entry.getValue();
644         }
645 
646         /**
647          * Returns the key corresponding to this entry.
648          *
649          * @return the key corresponding to this entry
650          */
getKey()651         public K getKey() {
652             return key;
653         }
654 
655         /**
656          * Returns the value corresponding to this entry.
657          *
658          * @return the value corresponding to this entry
659          */
getValue()660         public V getValue() {
661             return value;
662         }
663 
664         /**
665          * Replaces the value corresponding to this entry with the specified
666          * value.
667          *
668          * @param value new value to be stored in this entry
669          * @return the old value corresponding to the entry
670          */
setValue(V value)671         public V setValue(V value) {
672             V oldValue = this.value;
673             this.value = value;
674             return oldValue;
675         }
676 
677         /**
678          * Compares the specified object with this entry for equality.
679          * Returns {@code true} if the given object is also a map entry and
680          * the two entries represent the same mapping.  More formally, two
681          * entries {@code e1} and {@code e2} represent the same mapping
682          * if<pre>
683          *   (e1.getKey()==null ?
684          *    e2.getKey()==null :
685          *    e1.getKey().equals(e2.getKey()))
686          *   &amp;&amp;
687          *   (e1.getValue()==null ?
688          *    e2.getValue()==null :
689          *    e1.getValue().equals(e2.getValue()))</pre>
690          * This ensures that the {@code equals} method works properly across
691          * different implementations of the {@code Map.Entry} interface.
692          *
693          * @param o object to be compared for equality with this map entry
694          * @return {@code true} if the specified object is equal to this map
695          *         entry
696          * @see    #hashCode
697          */
equals(Object o)698         public boolean equals(Object o) {
699             return o instanceof Map.Entry<?, ?> e
700                     && eq(key, e.getKey())
701                     && eq(value, e.getValue());
702         }
703 
704         /**
705          * Returns the hash code value for this map entry.  The hash code
706          * of a map entry {@code e} is defined to be: <pre>
707          *   (e.getKey()==null   ? 0 : e.getKey().hashCode()) ^
708          *   (e.getValue()==null ? 0 : e.getValue().hashCode())</pre>
709          * This ensures that {@code e1.equals(e2)} implies that
710          * {@code e1.hashCode()==e2.hashCode()} for any two Entries
711          * {@code e1} and {@code e2}, as required by the general
712          * contract of {@link Object#hashCode}.
713          *
714          * @return the hash code value for this map entry
715          * @see    #equals
716          */
hashCode()717         public int hashCode() {
718             return (key   == null ? 0 :   key.hashCode()) ^
719                    (value == null ? 0 : value.hashCode());
720         }
721 
722         /**
723          * Returns a String representation of this map entry.  This
724          * implementation returns the string representation of this
725          * entry's key followed by the equals character ("{@code =}")
726          * followed by the string representation of this entry's value.
727          *
728          * @return a String representation of this map entry
729          */
toString()730         public String toString() {
731             return key + "=" + value;
732         }
733 
734     }
735 
736     /**
737      * An unmodifiable Entry maintaining a key and a value.  This class
738      * does not support the {@code setValue} method. Instances of
739      * this class are not associated with any map nor with any map's
740      * entry-set view.
741      *
742      * @apiNote
743      * Instances of this class are not necessarily immutable, as the key
744      * and value may be mutable. An instance of <i>this specific class</i>
745      * is unmodifiable, because the key and value references cannot be
746      * changed. A reference of this <i>type</i> may not be unmodifiable,
747      * as a subclass may be modifiable or may provide the appearance of modifiability.
748      * <p>
749      * This class may be convenient in methods that return thread-safe snapshots of
750      * key-value mappings. For alternatives, see the
751      * {@link Map#entry Map::entry} and {@link Map.Entry#copyOf Map.Entry::copyOf}
752      * methods.
753      *
754      * @param <K> the type of the keys
755      * @param <V> the type of the value
756      * @since 1.6
757      */
758     public static class SimpleImmutableEntry<K,V>
759         implements Entry<K,V>, java.io.Serializable
760     {
761         @java.io.Serial
762         private static final long serialVersionUID = 7138329143949025153L;
763 
764         @SuppressWarnings("serial") // Not statically typed as Serializable
765         private final K key;
766         @SuppressWarnings("serial") // Not statically typed as Serializable
767         private final V value;
768 
769         /**
770          * Creates an entry representing a mapping from the specified
771          * key to the specified value.
772          *
773          * @param key the key represented by this entry
774          * @param value the value represented by this entry
775          */
SimpleImmutableEntry(K key, V value)776         public SimpleImmutableEntry(K key, V value) {
777             this.key   = key;
778             this.value = value;
779         }
780 
781         /**
782          * Creates an entry representing the same mapping as the
783          * specified entry.
784          *
785          * @param entry the entry to copy
786          */
SimpleImmutableEntry(Entry<? extends K, ? extends V> entry)787         public SimpleImmutableEntry(Entry<? extends K, ? extends V> entry) {
788             this.key   = entry.getKey();
789             this.value = entry.getValue();
790         }
791 
792         /**
793          * Returns the key corresponding to this entry.
794          *
795          * @return the key corresponding to this entry
796          */
getKey()797         public K getKey() {
798             return key;
799         }
800 
801         /**
802          * Returns the value corresponding to this entry.
803          *
804          * @return the value corresponding to this entry
805          */
getValue()806         public V getValue() {
807             return value;
808         }
809 
810         /**
811          * Replaces the value corresponding to this entry with the specified
812          * value (optional operation).  This implementation simply throws
813          * {@code UnsupportedOperationException}, as this class implements
814          * an unmodifiable map entry.
815          *
816          * @implSpec
817          * The implementation in this class always throws {@code UnsupportedOperationException}.
818          *
819          * @param value new value to be stored in this entry
820          * @return (Does not return)
821          * @throws UnsupportedOperationException always
822          */
setValue(V value)823         public V setValue(V value) {
824             throw new UnsupportedOperationException();
825         }
826 
827         /**
828          * Compares the specified object with this entry for equality.
829          * Returns {@code true} if the given object is also a map entry and
830          * the two entries represent the same mapping.  More formally, two
831          * entries {@code e1} and {@code e2} represent the same mapping
832          * if<pre>
833          *   (e1.getKey()==null ?
834          *    e2.getKey()==null :
835          *    e1.getKey().equals(e2.getKey()))
836          *   &amp;&amp;
837          *   (e1.getValue()==null ?
838          *    e2.getValue()==null :
839          *    e1.getValue().equals(e2.getValue()))</pre>
840          * This ensures that the {@code equals} method works properly across
841          * different implementations of the {@code Map.Entry} interface.
842          *
843          * @param o object to be compared for equality with this map entry
844          * @return {@code true} if the specified object is equal to this map
845          *         entry
846          * @see    #hashCode
847          */
equals(Object o)848         public boolean equals(Object o) {
849             return o instanceof Map.Entry<?, ?> e
850                     && eq(key, e.getKey())
851                     && eq(value, e.getValue());
852         }
853 
854         /**
855          * Returns the hash code value for this map entry.  The hash code
856          * of a map entry {@code e} is defined to be: <pre>
857          *   (e.getKey()==null   ? 0 : e.getKey().hashCode()) ^
858          *   (e.getValue()==null ? 0 : e.getValue().hashCode())</pre>
859          * This ensures that {@code e1.equals(e2)} implies that
860          * {@code e1.hashCode()==e2.hashCode()} for any two Entries
861          * {@code e1} and {@code e2}, as required by the general
862          * contract of {@link Object#hashCode}.
863          *
864          * @return the hash code value for this map entry
865          * @see    #equals
866          */
hashCode()867         public int hashCode() {
868             return (key   == null ? 0 :   key.hashCode()) ^
869                    (value == null ? 0 : value.hashCode());
870         }
871 
872         /**
873          * Returns a String representation of this map entry.  This
874          * implementation returns the string representation of this
875          * entry's key followed by the equals character ("{@code =}")
876          * followed by the string representation of this entry's value.
877          *
878          * @return a String representation of this map entry
879          */
toString()880         public String toString() {
881             return key + "=" + value;
882         }
883     }
884 
885     /**
886      * Delegates all Collection methods to the provided non-sequenced map view,
887      * except add() and addAll(), which throw UOE. This provides the common
888      * implementation of each of the sequenced views of the SequencedMap.
889      * Each view implementation is a subclass that provides an instance of the
890      * non-sequenced view as a delegate and an implementation of reversed().
891      * Each view also inherits the default implementations for the sequenced
892      * methods from SequencedCollection or SequencedSet.
893      * <p>
894      * Ideally this would be a private class within SequencedMap, but private
895      * classes aren't permitted within interfaces.
896      * <p>
897      * The non-sequenced map view is obtained by calling the abstract view()
898      * method for each operation.
899      *
900      * @param <E> the view's element type
901      */
902     /* non-public */ abstract static class ViewCollection<E> implements Collection<E> {
uoe()903         UnsupportedOperationException uoe() { return new UnsupportedOperationException(); }
view()904         abstract Collection<E> view();
905 
add(E t)906         public boolean add(E t) { throw uoe(); }
addAll(Collection<? extends E> c)907         public boolean addAll(Collection<? extends E> c) { throw uoe(); }
clear()908         public void clear() { view().clear(); }
contains(Object o)909         public boolean contains(Object o) { return view().contains(o); }
containsAll(Collection<?> c)910         public boolean containsAll(Collection<?> c) { return view().containsAll(c); }
forEach(Consumer<? super E> c)911         public void forEach(Consumer<? super E> c) { view().forEach(c); }
isEmpty()912         public boolean isEmpty() { return view().isEmpty(); }
iterator()913         public Iterator<E> iterator() { return view().iterator(); }
parallelStream()914         public Stream<E> parallelStream() { return view().parallelStream(); }
remove(Object o)915         public boolean remove(Object o) { return view().remove(o); }
removeAll(Collection<?> c)916         public boolean removeAll(Collection<?> c) { return view().removeAll(c); }
removeIf(Predicate<? super E> filter)917         public boolean removeIf(Predicate<? super E> filter) { return view().removeIf(filter); }
retainAll(Collection<?> c)918         public boolean retainAll(Collection<?> c) { return view().retainAll(c); }
size()919         public int size() { return view().size(); }
spliterator()920         public Spliterator<E> spliterator() { return view().spliterator(); }
stream()921         public Stream<E> stream() { return view().stream(); }
toArray()922         public Object[] toArray() { return view().toArray(); }
toArray(IntFunction<T[]> generator)923         public <T> T[] toArray(IntFunction<T[]> generator) { return view().toArray(generator); }
toArray(T[] a)924         public <T> T[] toArray(T[] a) { return view().toArray(a); }
toString()925         public String toString() { return view().toString(); }
926     }
927 }
928