1 /*
2  * Copyright (c) 2000, 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 
28 /**
29  * <p>Hash table and linked list implementation of the {@code Set} interface,
30  * with well-defined encounter order.  This implementation differs from
31  * {@code HashSet} in that it maintains a doubly-linked list running through
32  * all of its entries.  This linked list defines the encounter order (iteration
33  * order), which is the order in which elements were inserted into the set
34  * (<i>insertion-order</i>). The least recently inserted element (the eldest) is
35  * first, and the youngest element is last. Note that encounter order is <i>not</i> affected
36  * if an element is <i>re-inserted</i> into the set with the {@code add} method.
37  * (An element {@code e} is reinserted into a set {@code s} if {@code s.add(e)} is
38  * invoked when {@code s.contains(e)} would return {@code true} immediately prior to
39  * the invocation.) The reverse-ordered view of this set is in the opposite order, with
40  * the youngest element appearing first and the eldest element appearing last. The encounter
41  * order of elements already in the set can be changed by using the
42  * {@link #addFirst addFirst} and {@link #addLast addLast} methods.
43  *
44  * <p>This implementation spares its clients from the unspecified, generally
45  * chaotic ordering provided by {@link HashSet}, without incurring the
46  * increased cost associated with {@link TreeSet}.  It can be used to
47  * produce a copy of a set that has the same order as the original, regardless
48  * of the original set's implementation:
49  * <pre>{@code
50  *     void foo(Set<String> s) {
51  *         Set<String> copy = new LinkedHashSet<>(s);
52  *         ...
53  *     }
54  * }</pre>
55  * This technique is particularly useful if a module takes a set on input,
56  * copies it, and later returns results whose order is determined by that of
57  * the copy.  (Clients generally appreciate having things returned in the same
58  * order they were presented.)
59  *
60  * <p>This class provides all of the optional {@link Set} and {@link SequencedSet}
61  * operations, and it permits null elements. Like {@code HashSet}, it provides constant-time
62  * performance for the basic operations ({@code add}, {@code contains} and
63  * {@code remove}), assuming the hash function disperses elements
64  * properly among the buckets.  Performance is likely to be just slightly
65  * below that of {@code HashSet}, due to the added expense of maintaining the
66  * linked list, with one exception: Iteration over a {@code LinkedHashSet}
67  * requires time proportional to the <i>size</i> of the set, regardless of
68  * its capacity.  Iteration over a {@code HashSet} is likely to be more
69  * expensive, requiring time proportional to its <i>capacity</i>.
70  *
71  * <p>A linked hash set has two parameters that affect its performance:
72  * <i>initial capacity</i> and <i>load factor</i>.  They are defined precisely
73  * as for {@code HashSet}.  Note, however, that the penalty for choosing an
74  * excessively high value for initial capacity is less severe for this class
75  * than for {@code HashSet}, as iteration times for this class are unaffected
76  * by capacity.
77  *
78  * <p><strong>Note that this implementation is not synchronized.</strong>
79  * If multiple threads access a linked hash set concurrently, and at least
80  * one of the threads modifies the set, it <em>must</em> be synchronized
81  * externally.  This is typically accomplished by synchronizing on some
82  * object that naturally encapsulates the set.
83  *
84  * If no such object exists, the set should be "wrapped" using the
85  * {@link Collections#synchronizedSet Collections.synchronizedSet}
86  * method.  This is best done at creation time, to prevent accidental
87  * unsynchronized access to the set: <pre>
88  *   Set s = Collections.synchronizedSet(new LinkedHashSet(...));</pre>
89  *
90  * <p>The iterators returned by this class's {@code iterator} method are
91  * <em>fail-fast</em>: if the set is modified at any time after the iterator
92  * is created, in any way except through the iterator's own {@code remove}
93  * method, the iterator will throw a {@link ConcurrentModificationException}.
94  * Thus, in the face of concurrent modification, the iterator fails quickly
95  * and cleanly, rather than risking arbitrary, non-deterministic behavior at
96  * an undetermined time in the future.
97  *
98  * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
99  * as it is, generally speaking, impossible to make any hard guarantees in the
100  * presence of unsynchronized concurrent modification.  Fail-fast iterators
101  * throw {@code ConcurrentModificationException} on a best-effort basis.
102  * Therefore, it would be wrong to write a program that depended on this
103  * exception for its correctness:   <i>the fail-fast behavior of iterators
104  * should be used only to detect bugs.</i>
105  *
106  * <p>This class is a member of the
107  * <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
108  * Java Collections Framework</a>.
109  *
110  * @param <E> the type of elements maintained by this set
111  *
112  * @author  Josh Bloch
113  * @see     Object#hashCode()
114  * @see     Collection
115  * @see     Set
116  * @see     HashSet
117  * @see     TreeSet
118  * @see     Hashtable
119  * @since   1.4
120  */
121 
122 public class LinkedHashSet<E>
123     extends HashSet<E>
124     implements SequencedSet<E>, Set<E>, Cloneable, java.io.Serializable {
125 
126     @java.io.Serial
127     private static final long serialVersionUID = -2851667679971038690L;
128 
129     /**
130      * Constructs a new, empty linked hash set with the specified initial
131      * capacity and load factor.
132      *
133      * @apiNote
134      * To create a {@code LinkedHashSet} with an initial capacity that accommodates
135      * an expected number of elements, use {@link #newLinkedHashSet(int) newLinkedHashSet}.
136      *
137      * @param      initialCapacity the initial capacity of the linked hash set
138      * @param      loadFactor      the load factor of the linked hash set
139      * @throws     IllegalArgumentException  if the initial capacity is less
140      *               than zero, or if the load factor is nonpositive
141      */
LinkedHashSet(int initialCapacity, float loadFactor)142     public LinkedHashSet(int initialCapacity, float loadFactor) {
143         super(initialCapacity, loadFactor, true);
144     }
145 
146     /**
147      * Constructs a new, empty linked hash set with the specified initial
148      * capacity and the default load factor (0.75).
149      *
150      * @apiNote
151      * To create a {@code LinkedHashSet} with an initial capacity that accommodates
152      * an expected number of elements, use {@link #newLinkedHashSet(int) newLinkedHashSet}.
153      *
154      * @param   initialCapacity   the initial capacity of the LinkedHashSet
155      * @throws  IllegalArgumentException if the initial capacity is less
156      *              than zero
157      */
LinkedHashSet(int initialCapacity)158     public LinkedHashSet(int initialCapacity) {
159         super(initialCapacity, .75f, true);
160     }
161 
162     /**
163      * Constructs a new, empty linked hash set with the default initial
164      * capacity (16) and load factor (0.75).
165      */
LinkedHashSet()166     public LinkedHashSet() {
167         super(16, .75f, true);
168     }
169 
170     /**
171      * Constructs a new linked hash set with the same elements as the
172      * specified collection.  The linked hash set is created with an initial
173      * capacity sufficient to hold the elements in the specified collection
174      * and the default load factor (0.75).
175      *
176      * @param c  the collection whose elements are to be placed into
177      *           this set
178      * @throws NullPointerException if the specified collection is null
179      */
LinkedHashSet(Collection<? extends E> c)180     public LinkedHashSet(Collection<? extends E> c) {
181         super(HashMap.calculateHashMapCapacity(Math.max(c.size(), 12)), .75f, true);
182         addAll(c);
183     }
184 
185     /**
186      * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
187      * and <em>fail-fast</em> {@code Spliterator} over the elements in this set.
188      *
189      * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
190      * {@link Spliterator#DISTINCT}, and {@code ORDERED}.  Implementations
191      * should document the reporting of additional characteristic values.
192      *
193      * @implNote
194      * The implementation creates a
195      * <em><a href="Spliterator.html#binding">late-binding</a></em> spliterator
196      * from the set's {@code Iterator}.  The spliterator inherits the
197      * <em>fail-fast</em> properties of the set's iterator.
198      * The created {@code Spliterator} additionally reports
199      * {@link Spliterator#SUBSIZED}.
200      *
201      * @return a {@code Spliterator} over the elements in this set
202      * @since 1.8
203      */
204     @Override
spliterator()205     public Spliterator<E> spliterator() {
206         return Spliterators.spliterator(this, Spliterator.DISTINCT | Spliterator.ORDERED);
207     }
208 
209     /**
210      * Creates a new, empty LinkedHashSet suitable for the expected number of elements.
211      * The returned set uses the default load factor of 0.75, and its initial capacity is
212      * generally large enough so that the expected number of elements can be added
213      * without resizing the set.
214      *
215      * @param numElements    the expected number of elements
216      * @param <T>         the type of elements maintained by the new set
217      * @return the newly created set
218      * @throws IllegalArgumentException if numElements is negative
219      * @since 19
220      */
newLinkedHashSet(int numElements)221     public static <T> LinkedHashSet<T> newLinkedHashSet(int numElements) {
222         if (numElements < 0) {
223             throw new IllegalArgumentException("Negative number of elements: " + numElements);
224         }
225         return new LinkedHashSet<>(HashMap.calculateHashMapCapacity(numElements));
226     }
227 
228     @SuppressWarnings("unchecked")
map()229     LinkedHashMap<E, Object> map() {
230         return (LinkedHashMap<E, Object>) map;
231     }
232 
233     /**
234      * {@inheritDoc}
235      * <p>
236      * If this set already contains the element, it is relocated if necessary so that it is
237      * first in encounter order.
238      *
239      * @since 21
240      */
addFirst(E e)241     public void addFirst(E e) {
242         map().putFirst(e, PRESENT);
243     }
244 
245     /**
246      * {@inheritDoc}
247      * <p>
248      * If this set already contains the element, it is relocated if necessary so that it is
249      * last in encounter order.
250      *
251      * @since 21
252      */
addLast(E e)253     public void addLast(E e) {
254         map().putLast(e, PRESENT);
255     }
256 
257     /**
258      * {@inheritDoc}
259      *
260      * @throws NoSuchElementException {@inheritDoc}
261      * @since 21
262      */
getFirst()263     public E getFirst() {
264         return map().sequencedKeySet().getFirst();
265     }
266 
267     /**
268      * {@inheritDoc}
269      *
270      * @throws NoSuchElementException {@inheritDoc}
271      * @since 21
272      */
getLast()273     public E getLast() {
274         return map().sequencedKeySet().getLast();
275     }
276 
277     /**
278      * {@inheritDoc}
279      *
280      * @throws NoSuchElementException {@inheritDoc}
281      * @since 21
282      */
removeFirst()283     public E removeFirst() {
284         return map().sequencedKeySet().removeFirst();
285     }
286 
287     /**
288      * {@inheritDoc}
289      *
290      * @throws NoSuchElementException {@inheritDoc}
291      * @since 21
292      */
removeLast()293     public E removeLast() {
294         return map().sequencedKeySet().removeLast();
295     }
296 
297     /**
298      * {@inheritDoc}
299      * <p>
300      * Modifications to the reversed view are permitted and will be propagated to this set.
301      * In addition, modifications to this set will be visible in the reversed view.
302      *
303      * @return {@inheritDoc}
304      * @since 21
305      */
reversed()306     public SequencedSet<E> reversed() {
307         class ReverseLinkedHashSetView extends AbstractSet<E> implements SequencedSet<E> {
308             public int size()                  { return LinkedHashSet.this.size(); }
309             public Iterator<E> iterator()      { return map().sequencedKeySet().reversed().iterator(); }
310             public boolean add(E e)            { return LinkedHashSet.this.add(e); }
311             public void addFirst(E e)          { LinkedHashSet.this.addLast(e); }
312             public void addLast(E e)           { LinkedHashSet.this.addFirst(e); }
313             public E getFirst()                { return LinkedHashSet.this.getLast(); }
314             public E getLast()                 { return LinkedHashSet.this.getFirst(); }
315             public E removeFirst()             { return LinkedHashSet.this.removeLast(); }
316             public E removeLast()              { return LinkedHashSet.this.removeFirst(); }
317             public SequencedSet<E> reversed()  { return LinkedHashSet.this; }
318             public Object[] toArray() { return map().keysToArray(new Object[map.size()], true); }
319             public <T> T[] toArray(T[] a) { return map().keysToArray(map.prepareArray(a), true); }
320         }
321 
322         return new ReverseLinkedHashSetView();
323     }
324 }
325