├── .gitignore ├── java └── util │ ├── KeyValueHolder.java │ ├── Stack.java │ ├── Enumeration.java │ ├── Iterator.java │ ├── Dictionary.java │ ├── concurrent │ ├── ConcurrentNavigableMap.java │ ├── TransferQueue.java │ └── CopyOnWriteArraySet.java │ ├── AbstractSet.java │ ├── AbstractQueue.java │ ├── ListIterator.java │ ├── LinkedHashSet.java │ ├── Queue.java │ ├── RegularEnumSet.java │ ├── AbstractSequentialList.java │ ├── PrimitiveIterator.java │ ├── SortedSet.java │ ├── JumboEnumSet.java │ ├── SortedMap.java │ ├── HashSet.java │ └── NavigableSet.java └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | .idea -------------------------------------------------------------------------------- /java/util/KeyValueHolder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015, 2017, 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 | import jdk.internal.vm.annotation.Stable; 29 | 30 | /** 31 | * An immutable container for a key and a value, suitable for use 32 | * in creating and populating {@code Map} instances. 33 | * 34 | *

This is a value-based 35 | * class; use of identity-sensitive operations (including reference equality 36 | * ({@code ==}), identity hash code, or synchronization) on instances of 37 | * {@code KeyValueHolder} may have unpredictable results and should be avoided. 38 | * 39 | * @apiNote 40 | * This class is not public. Instances can be created using the 41 | * {@link Map#entry Map.entry(k, v)} factory method, which is public. 42 | * 43 | *

This class differs from AbstractMap.SimpleImmutableEntry in the following ways: 44 | * it is not serializable, it is final, and its key and value must be non-null. 45 | * 46 | * @param the key type 47 | * @param the value type 48 | * 49 | * @see Map#ofEntries Map.ofEntries() 50 | * @since 9 51 | */ 52 | final class KeyValueHolder implements Map.Entry { 53 | @Stable 54 | final K key; 55 | @Stable 56 | final V value; 57 | 58 | KeyValueHolder(K k, V v) { 59 | key = Objects.requireNonNull(k); 60 | value = Objects.requireNonNull(v); 61 | } 62 | 63 | /** 64 | * Gets the key from this holder. 65 | * 66 | * @return the key 67 | */ 68 | @Override 69 | public K getKey() { 70 | return key; 71 | } 72 | 73 | /** 74 | * Gets the value from this holder. 75 | * 76 | * @return the value 77 | */ 78 | @Override 79 | public V getValue() { 80 | return value; 81 | } 82 | 83 | /** 84 | * Throws {@link UnsupportedOperationException}. 85 | * 86 | * @param value ignored 87 | * @return never returns normally 88 | */ 89 | @Override 90 | public V setValue(V value) { 91 | throw new UnsupportedOperationException("not supported"); 92 | } 93 | 94 | /** 95 | * Compares the specified object with this entry for equality. 96 | * Returns {@code true} if the given object is also a map entry and 97 | * the two entries' keys and values are equal. Note that key and 98 | * value are non-null, so equals() can be called safely on them. 99 | */ 100 | @Override 101 | public boolean equals(Object o) { 102 | if (!(o instanceof Map.Entry)) 103 | return false; 104 | Map.Entry e = (Map.Entry)o; 105 | return key.equals(e.getKey()) && value.equals(e.getValue()); 106 | } 107 | 108 | /** 109 | * Returns the hash code value for this map entry. The hash code 110 | * is {@code key.hashCode() ^ value.hashCode()}. Note that key and 111 | * value are non-null, so hashCode() can be called safely on them. 112 | */ 113 | @Override 114 | public int hashCode() { 115 | return key.hashCode() ^ value.hashCode(); 116 | } 117 | 118 | /** 119 | * Returns a String representation of this map entry. This 120 | * implementation returns the string representation of this 121 | * entry's key followed by the equals character ("{@code =}") 122 | * followed by the string representation of this entry's value. 123 | * 124 | * @return a String representation of this map entry 125 | */ 126 | @Override 127 | public String toString() { 128 | return key + "=" + value; 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /java/util/Stack.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 1994, 2010, 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 | * The {@code Stack} class represents a last-in-first-out 30 | * (LIFO) stack of objects. It extends class {@code Vector} with five 31 | * operations that allow a vector to be treated as a stack. The usual 32 | * {@code push} and {@code pop} operations are provided, as well as a 33 | * method to {@code peek} at the top item on the stack, a method to test 34 | * for whether the stack is {@code empty}, and a method to {@code search} 35 | * the stack for an item and discover how far it is from the top. 36 | *

37 | * When a stack is first created, it contains no items. 38 | * 39 | *

A more complete and consistent set of LIFO stack operations is 40 | * provided by the {@link Deque} interface and its implementations, which 41 | * should be used in preference to this class. For example: 42 | *

   {@code
 43 |  *   Deque stack = new ArrayDeque();}
44 | * 45 | * @author Jonathan Payne 46 | * @since 1.0 47 | */ 48 | public 49 | class Stack extends Vector { 50 | /** 51 | * Creates an empty Stack. 52 | */ 53 | public Stack() { 54 | } 55 | 56 | /** 57 | * Pushes an item onto the top of this stack. This has exactly 58 | * the same effect as: 59 | *
 60 |      * addElement(item)
61 | * 62 | * @param item the item to be pushed onto this stack. 63 | * @return the {@code item} argument. 64 | * @see java.util.Vector#addElement 65 | */ 66 | public E push(E item) { 67 | addElement(item); 68 | 69 | return item; 70 | } 71 | 72 | /** 73 | * Removes the object at the top of this stack and returns that 74 | * object as the value of this function. 75 | * 76 | * @return The object at the top of this stack (the last item 77 | * of the {@code Vector} object). 78 | * @throws EmptyStackException if this stack is empty. 79 | */ 80 | public synchronized E pop() { 81 | E obj; 82 | int len = size(); 83 | 84 | obj = peek(); 85 | removeElementAt(len - 1); 86 | 87 | return obj; 88 | } 89 | 90 | /** 91 | * Looks at the object at the top of this stack without removing it 92 | * from the stack. 93 | * 94 | * @return the object at the top of this stack (the last item 95 | * of the {@code Vector} object). 96 | * @throws EmptyStackException if this stack is empty. 97 | */ 98 | public synchronized E peek() { 99 | int len = size(); 100 | 101 | if (len == 0) 102 | throw new EmptyStackException(); 103 | return elementAt(len - 1); 104 | } 105 | 106 | /** 107 | * Tests if this stack is empty. 108 | * 109 | * @return {@code true} if and only if this stack contains 110 | * no items; {@code false} otherwise. 111 | */ 112 | public boolean empty() { 113 | return size() == 0; 114 | } 115 | 116 | /** 117 | * Returns the 1-based position where an object is on this stack. 118 | * If the object {@code o} occurs as an item in this stack, this 119 | * method returns the distance from the top of the stack of the 120 | * occurrence nearest the top of the stack; the topmost item on the 121 | * stack is considered to be at distance {@code 1}. The {@code equals} 122 | * method is used to compare {@code o} to the 123 | * items in this stack. 124 | * 125 | * @param o the desired object. 126 | * @return the 1-based position from the top of the stack where 127 | * the object is located; the return value {@code -1} 128 | * indicates that the object is not on the stack. 129 | */ 130 | public synchronized int search(Object o) { 131 | int i = lastIndexOf(o); 132 | 133 | if (i >= 0) { 134 | return size() - i; 135 | } 136 | return -1; 137 | } 138 | 139 | /** use serialVersionUID from JDK 1.0.2 for interoperability */ 140 | private static final long serialVersionUID = 1224463164541339165L; 141 | } 142 | -------------------------------------------------------------------------------- /java/util/Enumeration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 1994, 2015, 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 | * An object that implements the Enumeration interface generates a 30 | * series of elements, one at a time. Successive calls to the 31 | * {@code nextElement} method return successive elements of the 32 | * series. 33 | *

34 | * For example, to print all elements of a {@code Vector} v: 35 | *

 36 |  *   for (Enumeration<E> e = v.elements(); e.hasMoreElements();)
 37 |  *       System.out.println(e.nextElement());
38 | *

39 | * Methods are provided to enumerate through the elements of a 40 | * vector, the keys of a hashtable, and the values in a hashtable. 41 | * Enumerations are also used to specify the input streams to a 42 | * {@code SequenceInputStream}. 43 | * 44 | * @apiNote 45 | * The functionality of this interface is duplicated by the {@link Iterator} 46 | * interface. In addition, {@code Iterator} adds an optional remove operation, 47 | * and has shorter method names. New implementations should consider using 48 | * {@code Iterator} in preference to {@code Enumeration}. It is possible to 49 | * adapt an {@code Enumeration} to an {@code Iterator} by using the 50 | * {@link #asIterator} method. 51 | * 52 | * @see java.util.Iterator 53 | * @see java.io.SequenceInputStream 54 | * @see java.util.Enumeration#nextElement() 55 | * @see java.util.Hashtable 56 | * @see java.util.Hashtable#elements() 57 | * @see java.util.Hashtable#keys() 58 | * @see java.util.Vector 59 | * @see java.util.Vector#elements() 60 | * 61 | * @author Lee Boynton 62 | * @since 1.0 63 | */ 64 | public interface Enumeration { 65 | /** 66 | * Tests if this enumeration contains more elements. 67 | * 68 | * @return {@code true} if and only if this enumeration object 69 | * contains at least one more element to provide; 70 | * {@code false} otherwise. 71 | */ 72 | boolean hasMoreElements(); 73 | 74 | /** 75 | * Returns the next element of this enumeration if this enumeration 76 | * object has at least one more element to provide. 77 | * 78 | * @return the next element of this enumeration. 79 | * @exception NoSuchElementException if no more elements exist. 80 | */ 81 | E nextElement(); 82 | 83 | /** 84 | * Returns an {@link Iterator} that traverses the remaining elements 85 | * covered by this enumeration. Traversal is undefined if any methods 86 | * are called on this enumeration after the call to {@code asIterator}. 87 | * 88 | * @apiNote 89 | * This method is intended to help adapt code that produces 90 | * {@code Enumeration} instances to code that consumes {@code Iterator} 91 | * instances. For example, the {@link java.util.jar.JarFile#entries 92 | * JarFile.entries()} method returns an {@code Enumeration}. 93 | * This can be turned into an {@code Iterator}, and then the 94 | * {@code forEachRemaining()} method can be used: 95 | * 96 | *

{@code
 97 |      *     JarFile jarFile = ... ;
 98 |      *     jarFile.entries().asIterator().forEachRemaining(entry -> { ... });
 99 |      * }
100 | * 101 | * (Note that there is also a {@link java.util.jar.JarFile#stream 102 | * JarFile.stream()} method that returns a {@code Stream} of entries, 103 | * which may be more convenient in some cases.) 104 | * 105 | * @implSpec 106 | * The default implementation returns an {@code Iterator} whose 107 | * {@link Iterator#hasNext hasNext} method calls this Enumeration's 108 | * {@code hasMoreElements} method, whose {@link Iterator#next next} 109 | * method calls this Enumeration's {@code nextElement} method, and 110 | * whose {@link Iterator#remove remove} method throws 111 | * {@code UnsupportedOperationException}. 112 | * 113 | * @return an Iterator representing the remaining elements of this Enumeration 114 | * 115 | * @since 9 116 | */ 117 | default Iterator asIterator() { 118 | return new Iterator<>() { 119 | @Override public boolean hasNext() { 120 | return hasMoreElements(); 121 | } 122 | @Override public E next() { 123 | return nextElement(); 124 | } 125 | }; 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /java/util/Iterator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 1997, 2018, 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 | import java.util.function.Consumer; 29 | 30 | /** 31 | * An iterator over a collection. {@code Iterator} takes the place of 32 | * {@link Enumeration} in the Java Collections Framework. Iterators 33 | * differ from enumerations in two ways: 34 | * 35 | *
    36 | *
  • Iterators allow the caller to remove elements from the 37 | * underlying collection during the iteration with well-defined 38 | * semantics. 39 | *
  • Method names have been improved. 40 | *
41 | * 42 | *

This interface is a member of the 43 | * 44 | * Java Collections Framework. 45 | * 46 | * @apiNote 47 | * An {@link Enumeration} can be converted into an {@code Iterator} by 48 | * using the {@link Enumeration#asIterator} method. 49 | * 50 | * @param the type of elements returned by this iterator 51 | * 52 | * @author Josh Bloch 53 | * @see Collection 54 | * @see ListIterator 55 | * @see Iterable 56 | * @since 1.2 57 | */ 58 | public interface Iterator { 59 | /** 60 | * Returns {@code true} if the iteration has more elements. 61 | * (In other words, returns {@code true} if {@link #next} would 62 | * return an element rather than throwing an exception.) 63 | * 64 | * @return {@code true} if the iteration has more elements 65 | */ 66 | boolean hasNext(); 67 | 68 | /** 69 | * Returns the next element in the iteration. 70 | * 71 | * @return the next element in the iteration 72 | * @throws NoSuchElementException if the iteration has no more elements 73 | */ 74 | E next(); 75 | 76 | /** 77 | * Removes from the underlying collection the last element returned 78 | * by this iterator (optional operation). This method can be called 79 | * only once per call to {@link #next}. 80 | *

81 | * The behavior of an iterator is unspecified if the underlying collection 82 | * is modified while the iteration is in progress in any way other than by 83 | * calling this method, unless an overriding class has specified a 84 | * concurrent modification policy. 85 | *

86 | * The behavior of an iterator is unspecified if this method is called 87 | * after a call to the {@link #forEachRemaining forEachRemaining} method. 88 | * 89 | * @implSpec 90 | * The default implementation throws an instance of 91 | * {@link UnsupportedOperationException} and performs no other action. 92 | * 93 | * @throws UnsupportedOperationException if the {@code remove} 94 | * operation is not supported by this iterator 95 | * 96 | * @throws IllegalStateException if the {@code next} method has not 97 | * yet been called, or the {@code remove} method has already 98 | * been called after the last call to the {@code next} 99 | * method 100 | */ 101 | default void remove() { 102 | throw new UnsupportedOperationException("remove"); 103 | } 104 | 105 | /** 106 | * Performs the given action for each remaining element until all elements 107 | * have been processed or the action throws an exception. Actions are 108 | * performed in the order of iteration, if that order is specified. 109 | * Exceptions thrown by the action are relayed to the caller. 110 | *

111 | * The behavior of an iterator is unspecified if the action modifies the 112 | * collection in any way (even by calling the {@link #remove remove} method 113 | * or other mutator methods of {@code Iterator} subtypes), 114 | * unless an overriding class has specified a concurrent modification policy. 115 | *

116 | * Subsequent behavior of an iterator is unspecified if the action throws an 117 | * exception. 118 | * 119 | * @implSpec 120 | *

The default implementation behaves as if: 121 | *

{@code
122 |      *     while (hasNext())
123 |      *         action.accept(next());
124 |      * }
125 | * 126 | * @param action The action to be performed for each element 127 | * @throws NullPointerException if the specified action is null 128 | * @since 1.8 129 | */ 130 | default void forEachRemaining(Consumer action) { 131 | Objects.requireNonNull(action); 132 | while (hasNext()) 133 | action.accept(next()); 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /java/util/Dictionary.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 1995, 2004, 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 | * The {@code Dictionary} class is the abstract parent of any 30 | * class, such as {@code Hashtable}, which maps keys to values. 31 | * Every key and every value is an object. In any one {@code Dictionary} 32 | * object, every key is associated with at most one value. Given a 33 | * {@code Dictionary} and a key, the associated element can be looked up. 34 | * Any non-{@code null} object can be used as a key and as a value. 35 | *

36 | * As a rule, the {@code equals} method should be used by 37 | * implementations of this class to decide if two keys are the same. 38 | *

39 | * NOTE: This class is obsolete. New implementations should 40 | * implement the Map interface, rather than extending this class. 41 | * 42 | * @author unascribed 43 | * @see java.util.Map 44 | * @see java.lang.Object#equals(java.lang.Object) 45 | * @see java.lang.Object#hashCode() 46 | * @see java.util.Hashtable 47 | * @since 1.0 48 | */ 49 | public abstract 50 | class Dictionary { 51 | /** 52 | * Sole constructor. (For invocation by subclass constructors, typically 53 | * implicit.) 54 | */ 55 | public Dictionary() { 56 | } 57 | 58 | /** 59 | * Returns the number of entries (distinct keys) in this dictionary. 60 | * 61 | * @return the number of keys in this dictionary. 62 | */ 63 | public abstract int size(); 64 | 65 | /** 66 | * Tests if this dictionary maps no keys to value. The general contract 67 | * for the {@code isEmpty} method is that the result is true if and only 68 | * if this dictionary contains no entries. 69 | * 70 | * @return {@code true} if this dictionary maps no keys to values; 71 | * {@code false} otherwise. 72 | */ 73 | public abstract boolean isEmpty(); 74 | 75 | /** 76 | * Returns an enumeration of the keys in this dictionary. The general 77 | * contract for the keys method is that an {@code Enumeration} object 78 | * is returned that will generate all the keys for which this dictionary 79 | * contains entries. 80 | * 81 | * @return an enumeration of the keys in this dictionary. 82 | * @see java.util.Dictionary#elements() 83 | * @see java.util.Enumeration 84 | */ 85 | public abstract Enumeration keys(); 86 | 87 | /** 88 | * Returns an enumeration of the values in this dictionary. The general 89 | * contract for the {@code elements} method is that an 90 | * {@code Enumeration} is returned that will generate all the elements 91 | * contained in entries in this dictionary. 92 | * 93 | * @return an enumeration of the values in this dictionary. 94 | * @see java.util.Dictionary#keys() 95 | * @see java.util.Enumeration 96 | */ 97 | public abstract Enumeration elements(); 98 | 99 | /** 100 | * Returns the value to which the key is mapped in this dictionary. 101 | * The general contract for the {@code isEmpty} method is that if this 102 | * dictionary contains an entry for the specified key, the associated 103 | * value is returned; otherwise, {@code null} is returned. 104 | * 105 | * @return the value to which the key is mapped in this dictionary; 106 | * @param key a key in this dictionary. 107 | * {@code null} if the key is not mapped to any value in 108 | * this dictionary. 109 | * @exception NullPointerException if the {@code key} is {@code null}. 110 | * @see java.util.Dictionary#put(java.lang.Object, java.lang.Object) 111 | */ 112 | public abstract V get(Object key); 113 | 114 | /** 115 | * Maps the specified {@code key} to the specified 116 | * {@code value} in this dictionary. Neither the key nor the 117 | * value can be {@code null}. 118 | *

119 | * If this dictionary already contains an entry for the specified 120 | * {@code key}, the value already in this dictionary for that 121 | * {@code key} is returned, after modifying the entry to contain the 122 | * new element.

If this dictionary does not already have an entry 123 | * for the specified {@code key}, an entry is created for the 124 | * specified {@code key} and {@code value}, and {@code null} is 125 | * returned. 126 | *

127 | * The {@code value} can be retrieved by calling the 128 | * {@code get} method with a {@code key} that is equal to 129 | * the original {@code key}. 130 | * 131 | * @param key the hashtable key. 132 | * @param value the value. 133 | * @return the previous value to which the {@code key} was mapped 134 | * in this dictionary, or {@code null} if the key did not 135 | * have a previous mapping. 136 | * @exception NullPointerException if the {@code key} or 137 | * {@code value} is {@code null}. 138 | * @see java.lang.Object#equals(java.lang.Object) 139 | * @see java.util.Dictionary#get(java.lang.Object) 140 | */ 141 | public abstract V put(K key, V value); 142 | 143 | /** 144 | * Removes the {@code key} (and its corresponding 145 | * {@code value}) from this dictionary. This method does nothing 146 | * if the {@code key} is not in this dictionary. 147 | * 148 | * @param key the key that needs to be removed. 149 | * @return the value to which the {@code key} had been mapped in this 150 | * dictionary, or {@code null} if the key did not have a 151 | * mapping. 152 | * @exception NullPointerException if {@code key} is {@code null}. 153 | */ 154 | public abstract V remove(Object key); 155 | } 156 | -------------------------------------------------------------------------------- /java/util/concurrent/ConcurrentNavigableMap.java: -------------------------------------------------------------------------------- 1 | /* 2 | * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 3 | * 4 | * This code is free software; you can redistribute it and/or modify it 5 | * under the terms of the GNU General Public License version 2 only, as 6 | * published by the Free Software Foundation. Oracle designates this 7 | * particular file as subject to the "Classpath" exception as provided 8 | * by Oracle in the LICENSE file that accompanied this code. 9 | * 10 | * This code is distributed in the hope that it will be useful, but WITHOUT 11 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 12 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 13 | * version 2 for more details (a copy is included in the LICENSE file that 14 | * accompanied this code). 15 | * 16 | * You should have received a copy of the GNU General Public License version 17 | * 2 along with this work; if not, write to the Free Software Foundation, 18 | * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 19 | * 20 | * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 21 | * or visit www.oracle.com if you need additional information or have any 22 | * questions. 23 | */ 24 | 25 | /* 26 | * This file is available under and governed by the GNU General Public 27 | * License version 2 only, as published by the Free Software Foundation. 28 | * However, the following notice accompanied the original version of this 29 | * file: 30 | * 31 | * Written by Doug Lea with assistance from members of JCP JSR-166 32 | * Expert Group and released to the public domain, as explained at 33 | * http://creativecommons.org/publicdomain/zero/1.0/ 34 | */ 35 | 36 | package java.util.concurrent; 37 | 38 | import java.util.NavigableMap; 39 | import java.util.NavigableSet; 40 | 41 | /** 42 | * A {@link ConcurrentMap} supporting {@link NavigableMap} operations, 43 | * and recursively so for its navigable sub-maps. 44 | * 45 | *

This interface is a member of the 46 | * 47 | * Java Collections Framework. 48 | * 49 | * @author Doug Lea 50 | * @param the type of keys maintained by this map 51 | * @param the type of mapped values 52 | * @since 1.6 53 | */ 54 | public interface ConcurrentNavigableMap 55 | extends ConcurrentMap, NavigableMap 56 | { 57 | /** 58 | * @throws ClassCastException {@inheritDoc} 59 | * @throws NullPointerException {@inheritDoc} 60 | * @throws IllegalArgumentException {@inheritDoc} 61 | */ 62 | ConcurrentNavigableMap subMap(K fromKey, boolean fromInclusive, 63 | K toKey, boolean toInclusive); 64 | 65 | /** 66 | * @throws ClassCastException {@inheritDoc} 67 | * @throws NullPointerException {@inheritDoc} 68 | * @throws IllegalArgumentException {@inheritDoc} 69 | */ 70 | ConcurrentNavigableMap headMap(K toKey, boolean inclusive); 71 | 72 | /** 73 | * @throws ClassCastException {@inheritDoc} 74 | * @throws NullPointerException {@inheritDoc} 75 | * @throws IllegalArgumentException {@inheritDoc} 76 | */ 77 | ConcurrentNavigableMap tailMap(K fromKey, boolean inclusive); 78 | 79 | /** 80 | * @throws ClassCastException {@inheritDoc} 81 | * @throws NullPointerException {@inheritDoc} 82 | * @throws IllegalArgumentException {@inheritDoc} 83 | */ 84 | ConcurrentNavigableMap subMap(K fromKey, K toKey); 85 | 86 | /** 87 | * @throws ClassCastException {@inheritDoc} 88 | * @throws NullPointerException {@inheritDoc} 89 | * @throws IllegalArgumentException {@inheritDoc} 90 | */ 91 | ConcurrentNavigableMap headMap(K toKey); 92 | 93 | /** 94 | * @throws ClassCastException {@inheritDoc} 95 | * @throws NullPointerException {@inheritDoc} 96 | * @throws IllegalArgumentException {@inheritDoc} 97 | */ 98 | ConcurrentNavigableMap tailMap(K fromKey); 99 | 100 | /** 101 | * Returns a reverse order view of the mappings contained in this map. 102 | * The descending map is backed by this map, so changes to the map are 103 | * reflected in the descending map, and vice-versa. 104 | * 105 | *

The returned map has an ordering equivalent to 106 | * {@link java.util.Collections#reverseOrder(Comparator) Collections.reverseOrder}{@code (comparator())}. 107 | * The expression {@code m.descendingMap().descendingMap()} returns a 108 | * view of {@code m} essentially equivalent to {@code m}. 109 | * 110 | * @return a reverse order view of this map 111 | */ 112 | ConcurrentNavigableMap descendingMap(); 113 | 114 | /** 115 | * Returns a {@link NavigableSet} view of the keys contained in this map. 116 | * The set's iterator returns the keys in ascending order. 117 | * The set is backed by the map, so changes to the map are 118 | * reflected in the set, and vice-versa. The set supports element 119 | * removal, which removes the corresponding mapping from the map, 120 | * via the {@code Iterator.remove}, {@code Set.remove}, 121 | * {@code removeAll}, {@code retainAll}, and {@code clear} 122 | * operations. It does not support the {@code add} or {@code addAll} 123 | * operations. 124 | * 125 | *

The view's iterators and spliterators are 126 | * weakly consistent. 127 | * 128 | * @return a navigable set view of the keys in this map 129 | */ 130 | NavigableSet navigableKeySet(); 131 | 132 | /** 133 | * Returns a {@link NavigableSet} view of the keys contained in this map. 134 | * The set's iterator returns the keys in ascending order. 135 | * The set is backed by the map, so changes to the map are 136 | * reflected in the set, and vice-versa. The set supports element 137 | * removal, which removes the corresponding mapping from the map, 138 | * via the {@code Iterator.remove}, {@code Set.remove}, 139 | * {@code removeAll}, {@code retainAll}, and {@code clear} 140 | * operations. It does not support the {@code add} or {@code addAll} 141 | * operations. 142 | * 143 | *

The view's iterators and spliterators are 144 | * weakly consistent. 145 | * 146 | *

This method is equivalent to method {@code navigableKeySet}. 147 | * 148 | * @return a navigable set view of the keys in this map 149 | */ 150 | NavigableSet keySet(); 151 | 152 | /** 153 | * Returns a reverse order {@link NavigableSet} view of the keys contained in this map. 154 | * The set's iterator returns the keys in descending order. 155 | * The set is backed by the map, so changes to the map are 156 | * reflected in the set, and vice-versa. The set supports element 157 | * removal, which removes the corresponding mapping from the map, 158 | * via the {@code Iterator.remove}, {@code Set.remove}, 159 | * {@code removeAll}, {@code retainAll}, and {@code clear} 160 | * operations. It does not support the {@code add} or {@code addAll} 161 | * operations. 162 | * 163 | *

The view's iterators and spliterators are 164 | * weakly consistent. 165 | * 166 | * @return a reverse order navigable set view of the keys in this map 167 | */ 168 | NavigableSet descendingKeySet(); 169 | } 170 | -------------------------------------------------------------------------------- /java/util/concurrent/TransferQueue.java: -------------------------------------------------------------------------------- 1 | /* 2 | * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 3 | * 4 | * This code is free software; you can redistribute it and/or modify it 5 | * under the terms of the GNU General Public License version 2 only, as 6 | * published by the Free Software Foundation. Oracle designates this 7 | * particular file as subject to the "Classpath" exception as provided 8 | * by Oracle in the LICENSE file that accompanied this code. 9 | * 10 | * This code is distributed in the hope that it will be useful, but WITHOUT 11 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 12 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 13 | * version 2 for more details (a copy is included in the LICENSE file that 14 | * accompanied this code). 15 | * 16 | * You should have received a copy of the GNU General Public License version 17 | * 2 along with this work; if not, write to the Free Software Foundation, 18 | * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 19 | * 20 | * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 21 | * or visit www.oracle.com if you need additional information or have any 22 | * questions. 23 | */ 24 | 25 | /* 26 | * This file is available under and governed by the GNU General Public 27 | * License version 2 only, as published by the Free Software Foundation. 28 | * However, the following notice accompanied the original version of this 29 | * file: 30 | * 31 | * Written by Doug Lea with assistance from members of JCP JSR-166 32 | * Expert Group and released to the public domain, as explained at 33 | * http://creativecommons.org/publicdomain/zero/1.0/ 34 | */ 35 | 36 | package java.util.concurrent; 37 | 38 | /** 39 | * A {@link BlockingQueue} in which producers may wait for consumers 40 | * to receive elements. A {@code TransferQueue} may be useful for 41 | * example in message passing applications in which producers 42 | * sometimes (using method {@link #transfer}) await receipt of 43 | * elements by consumers invoking {@code take} or {@code poll}, while 44 | * at other times enqueue elements (via method {@code put}) without 45 | * waiting for receipt. 46 | * {@linkplain #tryTransfer(Object) Non-blocking} and 47 | * {@linkplain #tryTransfer(Object,long,TimeUnit) time-out} versions of 48 | * {@code tryTransfer} are also available. 49 | * A {@code TransferQueue} may also be queried, via {@link 50 | * #hasWaitingConsumer}, whether there are any threads waiting for 51 | * items, which is a converse analogy to a {@code peek} operation. 52 | * 53 | *

Like other blocking queues, a {@code TransferQueue} may be 54 | * capacity bounded. If so, an attempted transfer operation may 55 | * initially block waiting for available space, and/or subsequently 56 | * block waiting for reception by a consumer. Note that in a queue 57 | * with zero capacity, such as {@link SynchronousQueue}, {@code put} 58 | * and {@code transfer} are effectively synonymous. 59 | * 60 | *

This interface is a member of the 61 | * 62 | * Java Collections Framework. 63 | * 64 | * @since 1.7 65 | * @author Doug Lea 66 | * @param the type of elements held in this queue 67 | */ 68 | public interface TransferQueue extends BlockingQueue { 69 | /** 70 | * Transfers the element to a waiting consumer immediately, if possible. 71 | * 72 | *

More precisely, transfers the specified element immediately 73 | * if there exists a consumer already waiting to receive it (in 74 | * {@link #take} or timed {@link #poll(long,TimeUnit) poll}), 75 | * otherwise returning {@code false} without enqueuing the element. 76 | * 77 | * @param e the element to transfer 78 | * @return {@code true} if the element was transferred, else 79 | * {@code false} 80 | * @throws ClassCastException if the class of the specified element 81 | * prevents it from being added to this queue 82 | * @throws NullPointerException if the specified element is null 83 | * @throws IllegalArgumentException if some property of the specified 84 | * element prevents it from being added to this queue 85 | */ 86 | boolean tryTransfer(E e); 87 | 88 | /** 89 | * Transfers the element to a consumer, waiting if necessary to do so. 90 | * 91 | *

More precisely, transfers the specified element immediately 92 | * if there exists a consumer already waiting to receive it (in 93 | * {@link #take} or timed {@link #poll(long,TimeUnit) poll}), 94 | * else waits until the element is received by a consumer. 95 | * 96 | * @param e the element to transfer 97 | * @throws InterruptedException if interrupted while waiting, 98 | * in which case the element is not left enqueued 99 | * @throws ClassCastException if the class of the specified element 100 | * prevents it from being added to this queue 101 | * @throws NullPointerException if the specified element is null 102 | * @throws IllegalArgumentException if some property of the specified 103 | * element prevents it from being added to this queue 104 | */ 105 | void transfer(E e) throws InterruptedException; 106 | 107 | /** 108 | * Transfers the element to a consumer if it is possible to do so 109 | * before the timeout elapses. 110 | * 111 | *

More precisely, transfers the specified element immediately 112 | * if there exists a consumer already waiting to receive it (in 113 | * {@link #take} or timed {@link #poll(long,TimeUnit) poll}), 114 | * else waits until the element is received by a consumer, 115 | * returning {@code false} if the specified wait time elapses 116 | * before the element can be transferred. 117 | * 118 | * @param e the element to transfer 119 | * @param timeout how long to wait before giving up, in units of 120 | * {@code unit} 121 | * @param unit a {@code TimeUnit} determining how to interpret the 122 | * {@code timeout} parameter 123 | * @return {@code true} if successful, or {@code false} if 124 | * the specified waiting time elapses before completion, 125 | * in which case the element is not left enqueued 126 | * @throws InterruptedException if interrupted while waiting, 127 | * in which case the element is not left enqueued 128 | * @throws ClassCastException if the class of the specified element 129 | * prevents it from being added to this queue 130 | * @throws NullPointerException if the specified element is null 131 | * @throws IllegalArgumentException if some property of the specified 132 | * element prevents it from being added to this queue 133 | */ 134 | boolean tryTransfer(E e, long timeout, TimeUnit unit) 135 | throws InterruptedException; 136 | 137 | /** 138 | * Returns {@code true} if there is at least one consumer waiting 139 | * to receive an element via {@link #take} or 140 | * timed {@link #poll(long,TimeUnit) poll}. 141 | * The return value represents a momentary state of affairs. 142 | * 143 | * @return {@code true} if there is at least one waiting consumer 144 | */ 145 | boolean hasWaitingConsumer(); 146 | 147 | /** 148 | * Returns an estimate of the number of consumers waiting to 149 | * receive elements via {@link #take} or timed 150 | * {@link #poll(long,TimeUnit) poll}. The return value is an 151 | * approximation of a momentary state of affairs, that may be 152 | * inaccurate if consumers have completed or given up waiting. 153 | * The value may be useful for monitoring and heuristics, but 154 | * not for synchronization control. Implementations of this 155 | * method are likely to be noticeably slower than those for 156 | * {@link #hasWaitingConsumer}. 157 | * 158 | * @return the number of consumers waiting to receive elements 159 | */ 160 | int getWaitingConsumerCount(); 161 | } 162 | -------------------------------------------------------------------------------- /java/util/AbstractSet.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 1997, 2018, 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 | * This class provides a skeletal implementation of the {@code Set} 30 | * interface to minimize the effort required to implement this 31 | * interface.

32 | * 33 | * The process of implementing a set by extending this class is identical 34 | * to that of implementing a Collection by extending AbstractCollection, 35 | * except that all of the methods and constructors in subclasses of this 36 | * class must obey the additional constraints imposed by the {@code Set} 37 | * interface (for instance, the add method must not permit addition of 38 | * multiple instances of an object to a set).

39 | * 40 | * Note that this class does not override any of the implementations from 41 | * the {@code AbstractCollection} class. It merely adds implementations 42 | * for {@code equals} and {@code hashCode}.

43 | * 44 | * This class is a member of the 45 | * 46 | * Java Collections Framework. 47 | * 48 | * @param the type of elements maintained by this set 49 | * 50 | * @author Josh Bloch 51 | * @author Neal Gafter 52 | * @see Collection 53 | * @see AbstractCollection 54 | * @see Set 55 | * @since 1.2 56 | */ 57 | 58 | public abstract class AbstractSet extends AbstractCollection implements Set { 59 | /** 60 | * Sole constructor. (For invocation by subclass constructors, typically 61 | * implicit.) 62 | */ 63 | protected AbstractSet() { 64 | } 65 | 66 | // Comparison and hashing 67 | 68 | /** 69 | * Compares the specified object with this set for equality. Returns 70 | * {@code true} if the given object is also a set, the two sets have 71 | * the same size, and every member of the given set is contained in 72 | * this set. This ensures that the {@code equals} method works 73 | * properly across different implementations of the {@code Set} 74 | * interface.

75 | * 76 | * This implementation first checks if the specified object is this 77 | * set; if so it returns {@code true}. Then, it checks if the 78 | * specified object is a set whose size is identical to the size of 79 | * this set; if not, it returns false. If so, it returns 80 | * {@code containsAll((Collection) o)}. 81 | * 82 | * @param o object to be compared for equality with this set 83 | * @return {@code true} if the specified object is equal to this set 84 | */ 85 | public boolean equals(Object o) { 86 | if (o == this) 87 | return true; 88 | 89 | if (!(o instanceof Set)) 90 | return false; 91 | Collection c = (Collection) o; 92 | if (c.size() != size()) 93 | return false; 94 | try { 95 | return containsAll(c); 96 | } catch (ClassCastException | NullPointerException unused) { 97 | return false; 98 | } 99 | } 100 | 101 | /** 102 | * Returns the hash code value for this set. The hash code of a set is 103 | * defined to be the sum of the hash codes of the elements in the set, 104 | * where the hash code of a {@code null} element is defined to be zero. 105 | * This ensures that {@code s1.equals(s2)} implies that 106 | * {@code s1.hashCode()==s2.hashCode()} for any two sets {@code s1} 107 | * and {@code s2}, as required by the general contract of 108 | * {@link Object#hashCode}. 109 | * 110 | *

This implementation iterates over the set, calling the 111 | * {@code hashCode} method on each element in the set, and adding up 112 | * the results. 113 | * 114 | * @return the hash code value for this set 115 | * @see Object#equals(Object) 116 | * @see Set#equals(Object) 117 | */ 118 | public int hashCode() { 119 | int h = 0; 120 | Iterator i = iterator(); 121 | while (i.hasNext()) { 122 | E obj = i.next(); 123 | if (obj != null) 124 | h += obj.hashCode(); 125 | } 126 | return h; 127 | } 128 | 129 | /** 130 | * Removes from this set all of its elements that are contained in the 131 | * specified collection (optional operation). If the specified 132 | * collection is also a set, this operation effectively modifies this 133 | * set so that its value is the asymmetric set difference of 134 | * the two sets. 135 | * 136 | *

This implementation determines which is the smaller of this set 137 | * and the specified collection, by invoking the {@code size} 138 | * method on each. If this set has fewer elements, then the 139 | * implementation iterates over this set, checking each element 140 | * returned by the iterator in turn to see if it is contained in 141 | * the specified collection. If it is so contained, it is removed 142 | * from this set with the iterator's {@code remove} method. If 143 | * the specified collection has fewer elements, then the 144 | * implementation iterates over the specified collection, removing 145 | * from this set each element returned by the iterator, using this 146 | * set's {@code remove} method. 147 | * 148 | *

Note that this implementation will throw an 149 | * {@code UnsupportedOperationException} if the iterator returned by the 150 | * {@code iterator} method does not implement the {@code remove} method. 151 | * 152 | * @param c collection containing elements to be removed from this set 153 | * @return {@code true} if this set changed as a result of the call 154 | * @throws UnsupportedOperationException if the {@code removeAll} operation 155 | * is not supported by this set 156 | * @throws ClassCastException if the class of an element of this set 157 | * is incompatible with the specified collection 158 | * (optional) 159 | * @throws NullPointerException if this set contains a null element and the 160 | * specified collection does not permit null elements 161 | * (optional), 162 | * or if the specified collection is null 163 | * @see #remove(Object) 164 | * @see #contains(Object) 165 | */ 166 | public boolean removeAll(Collection c) { 167 | Objects.requireNonNull(c); 168 | boolean modified = false; 169 | 170 | if (size() > c.size()) { 171 | for (Object e : c) 172 | modified |= remove(e); 173 | } else { 174 | for (Iterator i = iterator(); i.hasNext(); ) { 175 | if (c.contains(i.next())) { 176 | i.remove(); 177 | modified = true; 178 | } 179 | } 180 | } 181 | return modified; 182 | } 183 | 184 | } 185 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JavaSourceCodeTranslate 2 | Java源码阅读计划 3 | 4 | **不管你是通过什么途径来到这个项目, 你都需要仔细阅读一下我对这个项目的一些想法** 5 | 6 | *update by lanyuanxiaoyao at 2018.11.13* 7 | 8 | # 版本 9 | 源码版本: [JDK 11.0.1 General-Availability Release](https://jdk.java.net/11/) 10 | 11 | # 译者 12 | LanyuanXiaoyao [Github](https://github.com/lanyuanxiaoyao) [Blog](http://lanyuanxiaoyao.com/) 13 | PengTan [Github](https://github.com/enterprising) 14 | Gintoms [Github](https://github.com/Gintoms) 15 | 16 | # 进度 17 | - concurrent 18 | - BlockingQueue (Translating... by *PengTan*) 19 | - ArrayList (Finished by *LanyuanXiaoyao*) 20 | - Collection (Translating... by *LanyuanXiaoyao*) 21 | 22 | # Q&A 23 | 24 | **Q** 为什么会有这个项目 25 | **A** 在学习编程的过程中, 我们时常会去网上找到别人的博客和文章, 看别人的解析总结和教学, 可我们真的学到了这份知识了吗? 26 | 事实上, 很多时候由于网文作者知识功底和文笔的原因, 一些博客或者网文总结出来的内容不一定非常准确和全面, 甚至是有遗漏的, 也有可能是因为侧重点的不同, 一些文章有选择地省略了一部分的内容, 再加上我们熟知的"复制黏贴一把梭", 作为读者的我们, 在这样的文章之上进行学习, 难免会建起空中楼阁. 如何解决学习二手知识带来的隐患, 方法几乎是只有一个, 那就是找到文章的本源, 也就是源码. 27 | 比如, 我们都知道`ArrayList`是一个基于数组的集合类, 然后呢? 然后就没有然后了, 关于其原理与实现的思路, 或者说一些实现的关键点, 我们几乎是抓瞎的, 勉强说出一两个, 但也不成体系, 这样的知识, 无限接近于没有, 而通过阅读`ArrayList`的源码, 我们就可以知道, 哪怕是一个简单的`add()`方法, 作者为了提高执行效率, 仍然事无巨细地运用了Java虚拟机将35个字节以下的方法进行内联编译处理这样的特性, 可以说是把性能用到了极致, 这些都是一些现成的文章里看不到的. 可以想象得到, Java源码中蕴涵着无穷的宝藏等着我们挖掘. 28 | 通过阅读优秀的源码可以提升自己的代码能力, 关于这一点已经是毋庸置疑, 但是我们也都知道, 阅读源码是一件无比枯燥的事情, 而生活中还有很多诱惑, 面对大篇大篇的源码, 大部分人, 包括我在内, 如果就这样一头扎进去就开始读, 不出几天就崩溃了, 所以我们必须要找到一个借口来让我们可以静下心来踏踏实实地一行一行把源码啃完, 于是**翻译注释**就成为了阅读源码的借口. 29 | Java的源码是世界上公认的最优秀的源码之一, 其中关于各种数据类型以及算法的实现, 都是教科书级别的, 至于为什么是教科书级别的呢? 因为Java里有一些算法的实现, 干脆就是提出算法本身的创作者写的, 还有什么比这更高级别的学习资料呢? Java经过了多年的迭代, 其中数据结构与算法的实现都经过了时间的考验, 稳健无比, 一些设计模式的使用更是炉火纯青, 所以从Java源码能学到的东西, 绝对不止一星半点. 更重要的是, Java源码的注释真的是详细到令人赞叹, 一些算法或者数据结构的要点, 十分直白地写在了类的开头, 很多细节都在注释里面一一说明, 面对如此良心的"教程", 我们怎么忍心拒绝, 所以直接阅读Java源码获得的知识, 远比在网上搜索一些博文来得要更丰富和准确. 30 | 所以这个项目就是一个以翻译注释为借口的源码阅读计划. 31 | **纸上得来终觉浅, 绝知此事要躬行.** 32 | 33 | **Q** 为什么只有Java的集合类 34 | **A** 没有人可以否认Java的体系实在是太庞大了, 随便拿出一个包, 都可以出一本书了, 所以秉承着贪多嚼不烂的原则, 这个项目决定从一点一滴开始做起, 为什么将集合类作为一个开端, 主要是集合是我们平常代码里用得最多的数据结构, `ArrayList`, `HashMap`都是已经被用到烂的数据结构, 所以从最熟悉的部分入手, 会比一些不常用的类来得要实用一些, 当然还有一个原因就是如果你要参加面试, 集合类几乎是必问的问题类型了, 这也从侧面说明了集合类的重要性, 所以项目就从集合类开始了. 35 | 另一个原因是`util`包下的类都比较独立, 一个类就是一个独立的功能, 不需要好几个类共同完成一个功能, 学习起来也自然就比较简单, 最起码你不需要再几个类的方法之间切来切去, 当然也为了避免一些干扰, 我也把`util`包下一些无关集合的类都删掉了, 当集合类的阅读计划已经完成(能做完这个就已经很厉害了额...), 或者觉得可以开始下一阶段的时候, 再把下一阶段的源码补充进来. 36 | 37 | **Q** 这个项目的进度怎么把控 38 | **A** 没有把控, 翻译只是一个借口, 我并没有想要推出一份Java中文API, 尽管这么做听起来很酷, 但这个"翻译"项目的最终目的只是帮助我们阅读源码来提高自己, 提高自己需要花多少时间, 谁也说不好, 所以也就不存在进度, 再说了, 本来就没有要输出什么明确的产品, 而且最重要最宝贵的财富是阅读源码的过程, 这个东西远远不是直接拿到一份现成的翻译成果可以相比的, 追求进度, 最终很容易得不偿失, 陷入为了翻译而翻译的困境. 39 | 另外, 阅读源码是一件非常繁琐而且枯燥的事情, **绝对不是短时间内可以完成的**, 所以早一天或者晚一天并不会产生质变, **重要的是坚持**, 每天只看几个方法, 一周也能有非常可观的积累, 有人说那总得有个安排吧, 我想说学习是自己的事情, 请自己把控. 40 | 41 | **Q** 既然自己阅读源码效果这么好, 为什么还要与人合作 42 | **A** 不可否认的是, 如果可以一个人通读Java的全部源码并且有自己的理解, 那当然是最好,但人的精力是有限的, 将自己所有的时间都放在这件事上并不现实, 而我们的知识也不知道什么时候会被用上, 比如突如其来的面试? 所以适当地提高效率是非常有益的事情, 合作就成了不二选择. 43 | 前文也说过, 阅读别人的二手知识容易受到别人主观总结的影响, 但这个项目的初衷不是拒绝二手知识吗? 这岂不是有了冲突? **鱼和熊掌不可兼得**, 效率与初衷产生了冲突是很常见的事情, 对于这个问题, 我觉得解决的方式出在合作的方式上, 一个合理的合作方式可以有效地平衡自己读源码和别人读源码之间的关系. 这个合理的合作方式就是: **将review别人的翻译当做第一要事**. **如果我们只关心自己翻译的注释和看过的代码, 那么合作将毫无意义**, 提高效率的前提就是在同样的时间里面, 你可以阅读到更多的源码, 通过翻译打破英语注释带来的隔阂, 帮助自己更快地了解代码的流程和逻辑, 这也是学习的一种, 而且在这个项目中有一个天然的优势, 那就是翻译注释在一定程度上摒除了个人的见解, 所以即使我们读的是别人翻译后的注释, 也不会影响我们对原意的把握, 这也是对二手知识隐患的一种处理方式吧. 44 | 总得来说, 我们是通过阅读源码的注释来学习源码, 翻译源码是促进自己对源码理解的一种手段, 任何时候都要将学习放在首位, 而不是速度, 当然, 速度快效率高肯定是不会被嫌弃的. 45 | 46 | **Q** 我该如何加入到项目里 47 | **A** 抱歉, 我并不打算随意地加入更多的合作者, 理由有几个, 一是时间有限, 精力有限, 按照目前的规模, 如果每个人翻译一个类的话, 那么在一段不短的时间里面, 我将需要同时跟进三个类的源码, 这对我来说是否是一个负担还是未知数, 所以目前也处于试水的阶段, 除了我以外的另外两个人, 是我在生活中的业内好友, 我对他们的责任心和技术能力都有非常强的信心, 我认为他们可以胜任这个项目想要完成的事, 不会轻易中断自己的学习, 话说到这里了, 也希望看到这里的你们两个人可以好好坚持下去, (滑稽.jpg). 48 | 另一个原因是这个项目的模式更像一个学习小组, 如果小组里的人互相认识, 那当然可以更方便地交流和合作, 因为阅读源码这个事, 总得自己亲自动手才有作用. 所以如果你不认识我的话, 我更建议你fork这个项目, 或者直接自己搭一个仓库, 将自己的小伙伴带入其中, 行成一个新的学习小组, 也不再局限于Java源码, 还可以是Spring源码, C++源码之类的. 49 | 50 | **Q** 我可以修改别人不通顺的翻译吗 51 | **A** 原则上是尽可能不要改动其他人的翻译, 因为翻译这种东西还是有一定的主观性的, 大家的水平都是半斤八两, 很难说一些遣词造句是谁更好, 而且改动别人的工作成果本身也不是一件令人觉得尊重的事情, 所以没事别瞎改别人的翻译, 就好像不要随便改别人的代码一样. 52 | 但是**这并不意味着有错误就不指出来, 相反, 指出错误这件事是值得提倡的**, 我把这里分为两种情况: 53 | 1. 一些字词翻译错误(注意, 是翻译错误, 而不是风格不合自己的口味), 一些代码的理解有歧义等, 这些**具有决定性的错误**是非常需要提出来的, 这也是整个学习的过程中非常重要的一个步骤, 就像review代码一样, 但是在原文上修改, 不仅让不知道前文的人一头雾水, 也会让译文作者不明所以, 所以我不提倡在原文改动错误, 而是通过**在原文的行末或另起一行, 说明错误的原因, 以及修改的意见, 当然署名也是必须的**, 译文的原作者也最好不要改动自己的错误, 尽可能地保留现场, 留下学习的材料, 哪怕是把注释这一房半亩地写成了评论区都没有关系, 当然啦, 对于原作者来说, 如果没有被人发现的话, 还是赶紧改回来吧, (狗头.jpg). 54 | 2. 一些风格上不合适导致出现了歧义(注意, 是出现了歧义, 影响了理解, 而不是风格不合自己的口味), 一些字词的使用不具有通用型, 造成了理解上的障碍, 这个时候, 仍然不要直接修改, 而是在字词之后, 使用括号将自己的建议写下, 原作者看到了修改建议之后, 酌情对不合适的语句和字词进行修改, 然后删掉修改建议. 55 | 56 | # 翻译 57 | 这里将尽可能地描述如何开展翻译源码注释的工作, 这是我自己总结的一些工作步骤, 旨在提高学习的效率, 统一工作的模式和风格. 58 | 59 | 1. 大段的多行注释, 在一整段注释的下方另起一段进行翻译, 可以避免原文与译文混淆在一起 60 | ```java 61 | /** 62 | * The array buffer into which the elements of the ArrayList are stored. 63 | * The capacity of the ArrayList is the length of this array buffer. Any 64 | * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA 65 | * will be expanded to DEFAULT_CAPACITY when the first element is added. 66 | * 67 | * ArrayList里的元素都被存储在这个数组缓存里. ArrayList的容量就是这个数组缓存的 68 | * 容量. 每一个空的ArrayList, 并且elementData等于DEFAULTCAPACITY_EMPTY_ELEMENTDATA 69 | * 的时候, 会在第一次添加元素的时候自动把容量增加到DEFAULT_CAPACITY(默认的初始 70 | * 化容量) 71 | */ 72 | transient Object[] elementData; 73 | ``` 74 | 2. 翻译的排版尽可能与源码注释相匹配, 当然也不需要过于追求排版, 美观即可 75 | 3. 较短的一句话描述, 或是一个单词短语的注释, 可以在行末空格后直接补充 76 | ```java 77 | /** 78 | * Constructs an empty list with the specified initial capacity. 79 | * 80 | * 构造一个指定的容量的空列表 81 | * 82 | * @param initialCapacity the initial capacity of the list 列表初始化的容量 83 | * @throws IllegalArgumentException if the specified initial capacity 84 | * is negative 如果指定的容量是一个非法的值 85 | */ 86 | ``` 87 | 4. 代码内的双斜杠注释, 可以选择行末空格后直接补充, 如果遇到一段话分开两行的, 在整段话后使用原排版进行补充 88 | ```java 89 | final int expectedModCount = modCount; 90 | // ArrayList can be subclassed and given arbitrary behavior, but we can 91 | // still deal with the common case where o is ArrayList precisely 92 | // ArrayList可以被继承并随意增加行为, 但通常情况下, 如果o是ArrayList的话我们 93 | // 仍然可以处理通用的部分. 94 | boolean equal = (o.getClass() == ArrayList.class) 95 | ? equalsArrayList((ArrayList) o) 96 | : equalsRange((List) o, 0, size); 97 | ``` 98 | 5. 对于觉得需要补充描述的大段注释, 在翻译后, 使用括号将主动补充的内容标记出来 99 | ```java 100 | /** 101 | * This helper method split out from add(E) to keep method 102 | * bytecode size under 35 (the -XX:MaxInlineSize default value), 103 | * which helps when add(E) is called in a C1-compiled loop. 104 | * 105 | * 这个辅助方法是从add(E)方法中分离出来的, 为的是确保(add(E))方法 106 | * 的字节码大小在35(-XX:MaxInlineSize参数的默认值)以下, 使得add(E) 107 | * 方法可以在一个编译循环中被调用. 108 | * 109 | * (在Java虚拟机中, 有一些代码片段是经常用到而且体积非常小的, 比如Java 110 | * Bean中的getter和setter代码, 为了提高方法执行的效率, 这些方法会被 111 | * Java虚拟机内联编译到代码当中. 在Java虚拟机默认的设置当中, 只有方法 112 | * 的代码长度在35个字节以下, 才会被虚拟机做内联处理, 于是为了保证add(E) 113 | * 方法可以被虚拟机做内联处理, 才将这个方法中的操作拆分出来.) 114 | * 115 | * (关于内联 116 | * 调用某个方法的过程在虚拟机中实际上是将汇编代码的执行顺序转移到某段内存 117 | * 当中, 等到执行完毕之后, 再切换回到原来的位置, 继续向下执行, 这种转移操 118 | * 作要求在转去前要保护现场并记忆执行的地址. 转回后先要恢复现场, 并按原来保 119 | * 存地址继续执行. 也就是通常说的压栈和出栈。因此, 函数调用要有一定的时间 120 | * 和空间方面的开销. 那么对于那些函数体代码不是很大,又频繁调用的函数来说, 121 | * 这个时间和空间的消耗会很大. 122 | * 内联处理实际上就是将存在别的地方的方法的代码, 直接替换到原来正常顺序中 123 | * 调用该方法的位置上, 这样就不存在跳转的问题了. 类似于C语言中的define.) 124 | * 125 | */ 126 | private void add(E e, Object[] elementData, int s) { 127 | if (s == elementData.length) 128 | elementData = grow(); 129 | elementData[s] = e; 130 | size = s + 1; 131 | } 132 | ``` 133 | 6. 对于一些编程时常见的词汇, 不需要翻译为中文, 比如`list`, `map`是大部分程序员的通用叫法, 如果强行翻译为`列表`和`键值对`反而不利于理解, 更别说`Set`你打算怎么翻译呢 134 | 7. 翻译的原则是忠于原文, 但不是逐字翻译, 我们都不是什么专业的翻译人员, 过于苛责字句翻译的准确性属于舍本逐末, 我们的翻译应当追求的是将原文的意思表达清楚, 一些语气词或者一些语序, 可以不必在意, 但切记, 关键的知识点一定要再三斟酌再表达出来 135 | 8. 尽管Java源码的注释非常详细, 但是在代码中对于一些流程的说明几乎没有, 因为Java的注释数据纲领性的, 但是具体到某一行的代码的时候, 就没有说明了, 这里就是我们需要主动输出知识的时候了, 凡是觉得需要说明的代码, 不要吝啬自己的智慧, 大方地加上自己的理解吧 136 | ```java 137 | public void add(int index, E element) { 138 | // 边界检查, 数组越界的异常会在这里被抛出 139 | rangeCheckForAdd(index); 140 | modCount++; 141 | final int s; 142 | Object[] elementData; 143 | // 容量不够了就先增加容量 144 | if ((s = size) == (elementData = this.elementData).length) 145 | elementData = grow(); 146 | // 将指定下标后的元素复制到下标+1的位置上 147 | System.arraycopy(elementData, index, 148 | elementData, index + 1, 149 | s - index); 150 | elementData[index] = element; 151 | size = s + 1; 152 | } 153 | ``` 154 | -------------------------------------------------------------------------------- /java/util/AbstractQueue.java: -------------------------------------------------------------------------------- 1 | /* 2 | * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 3 | * 4 | * This code is free software; you can redistribute it and/or modify it 5 | * under the terms of the GNU General Public License version 2 only, as 6 | * published by the Free Software Foundation. Oracle designates this 7 | * particular file as subject to the "Classpath" exception as provided 8 | * by Oracle in the LICENSE file that accompanied this code. 9 | * 10 | * This code is distributed in the hope that it will be useful, but WITHOUT 11 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 12 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 13 | * version 2 for more details (a copy is included in the LICENSE file that 14 | * accompanied this code). 15 | * 16 | * You should have received a copy of the GNU General Public License version 17 | * 2 along with this work; if not, write to the Free Software Foundation, 18 | * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 19 | * 20 | * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 21 | * or visit www.oracle.com if you need additional information or have any 22 | * questions. 23 | */ 24 | 25 | /* 26 | * This file is available under and governed by the GNU General Public 27 | * License version 2 only, as published by the Free Software Foundation. 28 | * However, the following notice accompanied the original version of this 29 | * file: 30 | * 31 | * Written by Doug Lea with assistance from members of JCP JSR-166 32 | * Expert Group and released to the public domain, as explained at 33 | * http://creativecommons.org/publicdomain/zero/1.0/ 34 | */ 35 | 36 | package java.util; 37 | 38 | /** 39 | * This class provides skeletal implementations of some {@link Queue} 40 | * operations. The implementations in this class are appropriate when 41 | * the base implementation does not allow {@code null} 42 | * elements. Methods {@link #add add}, {@link #remove remove}, and 43 | * {@link #element element} are based on {@link #offer offer}, {@link 44 | * #poll poll}, and {@link #peek peek}, respectively, but throw 45 | * exceptions instead of indicating failure via {@code false} or 46 | * {@code null} returns. 47 | * 48 | *

A {@code Queue} implementation that extends this class must 49 | * minimally define a method {@link Queue#offer} which does not permit 50 | * insertion of {@code null} elements, along with methods {@link 51 | * Queue#peek}, {@link Queue#poll}, {@link Collection#size}, and 52 | * {@link Collection#iterator}. Typically, additional methods will be 53 | * overridden as well. If these requirements cannot be met, consider 54 | * instead subclassing {@link AbstractCollection}. 55 | * 56 | *

This class is a member of the 57 | * 58 | * Java Collections Framework. 59 | * 60 | * @since 1.5 61 | * @author Doug Lea 62 | * @param the type of elements held in this queue 63 | */ 64 | public abstract class AbstractQueue 65 | extends AbstractCollection 66 | implements Queue { 67 | 68 | /** 69 | * Constructor for use by subclasses. 70 | */ 71 | protected AbstractQueue() { 72 | } 73 | 74 | /** 75 | * Inserts the specified element into this queue if it is possible to do so 76 | * immediately without violating capacity restrictions, returning 77 | * {@code true} upon success and throwing an {@code IllegalStateException} 78 | * if no space is currently available. 79 | * 80 | *

This implementation returns {@code true} if {@code offer} succeeds, 81 | * else throws an {@code IllegalStateException}. 82 | * 83 | * @param e the element to add 84 | * @return {@code true} (as specified by {@link Collection#add}) 85 | * @throws IllegalStateException if the element cannot be added at this 86 | * time due to capacity restrictions 87 | * @throws ClassCastException if the class of the specified element 88 | * prevents it from being added to this queue 89 | * @throws NullPointerException if the specified element is null and 90 | * this queue does not permit null elements 91 | * @throws IllegalArgumentException if some property of this element 92 | * prevents it from being added to this queue 93 | */ 94 | public boolean add(E e) { 95 | if (offer(e)) 96 | return true; 97 | else 98 | throw new IllegalStateException("Queue full"); 99 | } 100 | 101 | /** 102 | * Retrieves and removes the head of this queue. This method differs 103 | * from {@link #poll poll} only in that it throws an exception if this 104 | * queue is empty. 105 | * 106 | *

This implementation returns the result of {@code poll} 107 | * unless the queue is empty. 108 | * 109 | * @return the head of this queue 110 | * @throws NoSuchElementException if this queue is empty 111 | */ 112 | public E remove() { 113 | E x = poll(); 114 | if (x != null) 115 | return x; 116 | else 117 | throw new NoSuchElementException(); 118 | } 119 | 120 | /** 121 | * Retrieves, but does not remove, the head of this queue. This method 122 | * differs from {@link #peek peek} only in that it throws an exception if 123 | * this queue is empty. 124 | * 125 | *

This implementation returns the result of {@code peek} 126 | * unless the queue is empty. 127 | * 128 | * @return the head of this queue 129 | * @throws NoSuchElementException if this queue is empty 130 | */ 131 | public E element() { 132 | E x = peek(); 133 | if (x != null) 134 | return x; 135 | else 136 | throw new NoSuchElementException(); 137 | } 138 | 139 | /** 140 | * Removes all of the elements from this queue. 141 | * The queue will be empty after this call returns. 142 | * 143 | *

This implementation repeatedly invokes {@link #poll poll} until it 144 | * returns {@code null}. 145 | */ 146 | public void clear() { 147 | while (poll() != null) 148 | ; 149 | } 150 | 151 | /** 152 | * Adds all of the elements in the specified collection to this 153 | * queue. Attempts to addAll of a queue to itself result in 154 | * {@code IllegalArgumentException}. Further, the behavior of 155 | * this operation is undefined if the specified collection is 156 | * modified while the operation is in progress. 157 | * 158 | *

This implementation iterates over the specified collection, 159 | * and adds each element returned by the iterator to this 160 | * queue, in turn. A runtime exception encountered while 161 | * trying to add an element (including, in particular, a 162 | * {@code null} element) may result in only some of the elements 163 | * having been successfully added when the associated exception is 164 | * thrown. 165 | * 166 | * @param c collection containing elements to be added to this queue 167 | * @return {@code true} if this queue changed as a result of the call 168 | * @throws ClassCastException if the class of an element of the specified 169 | * collection prevents it from being added to this queue 170 | * @throws NullPointerException if the specified collection contains a 171 | * null element and this queue does not permit null elements, 172 | * or if the specified collection is null 173 | * @throws IllegalArgumentException if some property of an element of the 174 | * specified collection prevents it from being added to this 175 | * queue, or if the specified collection is this queue 176 | * @throws IllegalStateException if not all the elements can be added at 177 | * this time due to insertion restrictions 178 | * @see #add(Object) 179 | */ 180 | public boolean addAll(Collection c) { 181 | if (c == null) 182 | throw new NullPointerException(); 183 | if (c == this) 184 | throw new IllegalArgumentException(); 185 | boolean modified = false; 186 | for (E e : c) 187 | if (add(e)) 188 | modified = true; 189 | return modified; 190 | } 191 | 192 | } 193 | -------------------------------------------------------------------------------- /java/util/ListIterator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 1997, 2018, 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 | * An iterator for lists that allows the programmer 30 | * to traverse the list in either direction, modify 31 | * the list during iteration, and obtain the iterator's 32 | * current position in the list. A {@code ListIterator} 33 | * has no current element; its cursor position always 34 | * lies between the element that would be returned by a call 35 | * to {@code previous()} and the element that would be 36 | * returned by a call to {@code next()}. 37 | * An iterator for a list of length {@code n} has {@code n+1} possible 38 | * cursor positions, as illustrated by the carets ({@code ^}) below: 39 | *

 40 |  *                      Element(0)   Element(1)   Element(2)   ... Element(n-1)
 41 |  * cursor positions:  ^            ^            ^            ^                  ^
 42 |  * 
43 | * Note that the {@link #remove} and {@link #set(Object)} methods are 44 | * not defined in terms of the cursor position; they are defined to 45 | * operate on the last element returned by a call to {@link #next} or 46 | * {@link #previous()}. 47 | * 48 | *

This interface is a member of the 49 | * 50 | * Java Collections Framework. 51 | * 52 | * @author Josh Bloch 53 | * @see Collection 54 | * @see List 55 | * @see Iterator 56 | * @see Enumeration 57 | * @see List#listIterator() 58 | * @since 1.2 59 | */ 60 | public interface ListIterator extends Iterator { 61 | // Query Operations 62 | 63 | /** 64 | * Returns {@code true} if this list iterator has more elements when 65 | * traversing the list in the forward direction. (In other words, 66 | * returns {@code true} if {@link #next} would return an element rather 67 | * than throwing an exception.) 68 | * 69 | * @return {@code true} if the list iterator has more elements when 70 | * traversing the list in the forward direction 71 | */ 72 | boolean hasNext(); 73 | 74 | /** 75 | * Returns the next element in the list and advances the cursor position. 76 | * This method may be called repeatedly to iterate through the list, 77 | * or intermixed with calls to {@link #previous} to go back and forth. 78 | * (Note that alternating calls to {@code next} and {@code previous} 79 | * will return the same element repeatedly.) 80 | * 81 | * @return the next element in the list 82 | * @throws NoSuchElementException if the iteration has no next element 83 | */ 84 | E next(); 85 | 86 | /** 87 | * Returns {@code true} if this list iterator has more elements when 88 | * traversing the list in the reverse direction. (In other words, 89 | * returns {@code true} if {@link #previous} would return an element 90 | * rather than throwing an exception.) 91 | * 92 | * @return {@code true} if the list iterator has more elements when 93 | * traversing the list in the reverse direction 94 | */ 95 | boolean hasPrevious(); 96 | 97 | /** 98 | * Returns the previous element in the list and moves the cursor 99 | * position backwards. This method may be called repeatedly to 100 | * iterate through the list backwards, or intermixed with calls to 101 | * {@link #next} to go back and forth. (Note that alternating calls 102 | * to {@code next} and {@code previous} will return the same 103 | * element repeatedly.) 104 | * 105 | * @return the previous element in the list 106 | * @throws NoSuchElementException if the iteration has no previous 107 | * element 108 | */ 109 | E previous(); 110 | 111 | /** 112 | * Returns the index of the element that would be returned by a 113 | * subsequent call to {@link #next}. (Returns list size if the list 114 | * iterator is at the end of the list.) 115 | * 116 | * @return the index of the element that would be returned by a 117 | * subsequent call to {@code next}, or list size if the list 118 | * iterator is at the end of the list 119 | */ 120 | int nextIndex(); 121 | 122 | /** 123 | * Returns the index of the element that would be returned by a 124 | * subsequent call to {@link #previous}. (Returns -1 if the list 125 | * iterator is at the beginning of the list.) 126 | * 127 | * @return the index of the element that would be returned by a 128 | * subsequent call to {@code previous}, or -1 if the list 129 | * iterator is at the beginning of the list 130 | */ 131 | int previousIndex(); 132 | 133 | 134 | // Modification Operations 135 | 136 | /** 137 | * Removes from the list the last element that was returned by {@link 138 | * #next} or {@link #previous} (optional operation). This call can 139 | * only be made once per call to {@code next} or {@code previous}. 140 | * It can be made only if {@link #add} has not been 141 | * called after the last call to {@code next} or {@code previous}. 142 | * 143 | * @throws UnsupportedOperationException if the {@code remove} 144 | * operation is not supported by this list iterator 145 | * @throws IllegalStateException if neither {@code next} nor 146 | * {@code previous} have been called, or {@code remove} or 147 | * {@code add} have been called after the last call to 148 | * {@code next} or {@code previous} 149 | */ 150 | void remove(); 151 | 152 | /** 153 | * Replaces the last element returned by {@link #next} or 154 | * {@link #previous} with the specified element (optional operation). 155 | * This call can be made only if neither {@link #remove} nor {@link 156 | * #add} have been called after the last call to {@code next} or 157 | * {@code previous}. 158 | * 159 | * @param e the element with which to replace the last element returned by 160 | * {@code next} or {@code previous} 161 | * @throws UnsupportedOperationException if the {@code set} operation 162 | * is not supported by this list iterator 163 | * @throws ClassCastException if the class of the specified element 164 | * prevents it from being added to this list 165 | * @throws IllegalArgumentException if some aspect of the specified 166 | * element prevents it from being added to this list 167 | * @throws IllegalStateException if neither {@code next} nor 168 | * {@code previous} have been called, or {@code remove} or 169 | * {@code add} have been called after the last call to 170 | * {@code next} or {@code previous} 171 | */ 172 | void set(E e); 173 | 174 | /** 175 | * Inserts the specified element into the list (optional operation). 176 | * The element is inserted immediately before the element that 177 | * would be returned by {@link #next}, if any, and after the element 178 | * that would be returned by {@link #previous}, if any. (If the 179 | * list contains no elements, the new element becomes the sole element 180 | * on the list.) The new element is inserted before the implicit 181 | * cursor: a subsequent call to {@code next} would be unaffected, and a 182 | * subsequent call to {@code previous} would return the new element. 183 | * (This call increases by one the value that would be returned by a 184 | * call to {@code nextIndex} or {@code previousIndex}.) 185 | * 186 | * @param e the element to insert 187 | * @throws UnsupportedOperationException if the {@code add} method is 188 | * not supported by this list iterator 189 | * @throws ClassCastException if the class of the specified element 190 | * prevents it from being added to this list 191 | * @throws IllegalArgumentException if some aspect of this element 192 | * prevents it from being added to this list 193 | */ 194 | void add(E e); 195 | } 196 | -------------------------------------------------------------------------------- /java/util/LinkedHashSet.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2000, 2018, 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 | *

Hash table and linked list implementation of the {@code Set} interface, 30 | * with predictable iteration 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 iteration ordering, 33 | * which is the order in which elements were inserted into the set 34 | * (insertion-order). Note that insertion order is not affected 35 | * if an element is re-inserted into the set. (An element {@code e} 36 | * is reinserted into a set {@code s} if {@code s.add(e)} is invoked when 37 | * {@code s.contains(e)} would return {@code true} immediately prior to 38 | * the invocation.) 39 | * 40 | *

This implementation spares its clients from the unspecified, generally 41 | * chaotic ordering provided by {@link HashSet}, without incurring the 42 | * increased cost associated with {@link TreeSet}. It can be used to 43 | * produce a copy of a set that has the same order as the original, regardless 44 | * of the original set's implementation: 45 | *

 46 |  *     void foo(Set s) {
 47 |  *         Set copy = new LinkedHashSet(s);
 48 |  *         ...
 49 |  *     }
 50 |  * 
51 | * This technique is particularly useful if a module takes a set on input, 52 | * copies it, and later returns results whose order is determined by that of 53 | * the copy. (Clients generally appreciate having things returned in the same 54 | * order they were presented.) 55 | * 56 | *

This class provides all of the optional {@code Set} operations, and 57 | * permits null elements. Like {@code HashSet}, it provides constant-time 58 | * performance for the basic operations ({@code add}, {@code contains} and 59 | * {@code remove}), assuming the hash function disperses elements 60 | * properly among the buckets. Performance is likely to be just slightly 61 | * below that of {@code HashSet}, due to the added expense of maintaining the 62 | * linked list, with one exception: Iteration over a {@code LinkedHashSet} 63 | * requires time proportional to the size of the set, regardless of 64 | * its capacity. Iteration over a {@code HashSet} is likely to be more 65 | * expensive, requiring time proportional to its capacity. 66 | * 67 | *

A linked hash set has two parameters that affect its performance: 68 | * initial capacity and load factor. They are defined precisely 69 | * as for {@code HashSet}. Note, however, that the penalty for choosing an 70 | * excessively high value for initial capacity is less severe for this class 71 | * than for {@code HashSet}, as iteration times for this class are unaffected 72 | * by capacity. 73 | * 74 | *

Note that this implementation is not synchronized. 75 | * If multiple threads access a linked hash set concurrently, and at least 76 | * one of the threads modifies the set, it must be synchronized 77 | * externally. This is typically accomplished by synchronizing on some 78 | * object that naturally encapsulates the set. 79 | * 80 | * If no such object exists, the set should be "wrapped" using the 81 | * {@link Collections#synchronizedSet Collections.synchronizedSet} 82 | * method. This is best done at creation time, to prevent accidental 83 | * unsynchronized access to the set:

 84 |  *   Set s = Collections.synchronizedSet(new LinkedHashSet(...));
85 | * 86 | *

The iterators returned by this class's {@code iterator} method are 87 | * fail-fast: if the set is modified at any time after the iterator 88 | * is created, in any way except through the iterator's own {@code remove} 89 | * method, the iterator will throw a {@link ConcurrentModificationException}. 90 | * Thus, in the face of concurrent modification, the iterator fails quickly 91 | * and cleanly, rather than risking arbitrary, non-deterministic behavior at 92 | * an undetermined time in the future. 93 | * 94 | *

Note that the fail-fast behavior of an iterator cannot be guaranteed 95 | * as it is, generally speaking, impossible to make any hard guarantees in the 96 | * presence of unsynchronized concurrent modification. Fail-fast iterators 97 | * throw {@code ConcurrentModificationException} on a best-effort basis. 98 | * Therefore, it would be wrong to write a program that depended on this 99 | * exception for its correctness: the fail-fast behavior of iterators 100 | * should be used only to detect bugs. 101 | * 102 | *

This class is a member of the 103 | * 104 | * Java Collections Framework. 105 | * 106 | * @param the type of elements maintained by this set 107 | * 108 | * @author Josh Bloch 109 | * @see Object#hashCode() 110 | * @see Collection 111 | * @see Set 112 | * @see HashSet 113 | * @see TreeSet 114 | * @see Hashtable 115 | * @since 1.4 116 | */ 117 | 118 | public class LinkedHashSet 119 | extends HashSet 120 | implements Set, Cloneable, java.io.Serializable { 121 | 122 | private static final long serialVersionUID = -2851667679971038690L; 123 | 124 | /** 125 | * Constructs a new, empty linked hash set with the specified initial 126 | * capacity and load factor. 127 | * 128 | * @param initialCapacity the initial capacity of the linked hash set 129 | * @param loadFactor the load factor of the linked hash set 130 | * @throws IllegalArgumentException if the initial capacity is less 131 | * than zero, or if the load factor is nonpositive 132 | */ 133 | public LinkedHashSet(int initialCapacity, float loadFactor) { 134 | super(initialCapacity, loadFactor, true); 135 | } 136 | 137 | /** 138 | * Constructs a new, empty linked hash set with the specified initial 139 | * capacity and the default load factor (0.75). 140 | * 141 | * @param initialCapacity the initial capacity of the LinkedHashSet 142 | * @throws IllegalArgumentException if the initial capacity is less 143 | * than zero 144 | */ 145 | public LinkedHashSet(int initialCapacity) { 146 | super(initialCapacity, .75f, true); 147 | } 148 | 149 | /** 150 | * Constructs a new, empty linked hash set with the default initial 151 | * capacity (16) and load factor (0.75). 152 | */ 153 | public LinkedHashSet() { 154 | super(16, .75f, true); 155 | } 156 | 157 | /** 158 | * Constructs a new linked hash set with the same elements as the 159 | * specified collection. The linked hash set is created with an initial 160 | * capacity sufficient to hold the elements in the specified collection 161 | * and the default load factor (0.75). 162 | * 163 | * @param c the collection whose elements are to be placed into 164 | * this set 165 | * @throws NullPointerException if the specified collection is null 166 | */ 167 | public LinkedHashSet(Collection c) { 168 | super(Math.max(2*c.size(), 11), .75f, true); 169 | addAll(c); 170 | } 171 | 172 | /** 173 | * Creates a late-binding 174 | * and fail-fast {@code Spliterator} over the elements in this set. 175 | * 176 | *

The {@code Spliterator} reports {@link Spliterator#SIZED}, 177 | * {@link Spliterator#DISTINCT}, and {@code ORDERED}. Implementations 178 | * should document the reporting of additional characteristic values. 179 | * 180 | * @implNote 181 | * The implementation creates a 182 | * late-binding spliterator 183 | * from the set's {@code Iterator}. The spliterator inherits the 184 | * fail-fast properties of the set's iterator. 185 | * The created {@code Spliterator} additionally reports 186 | * {@link Spliterator#SUBSIZED}. 187 | * 188 | * @return a {@code Spliterator} over the elements in this set 189 | * @since 1.8 190 | */ 191 | @Override 192 | public Spliterator spliterator() { 193 | return Spliterators.spliterator(this, Spliterator.DISTINCT | Spliterator.ORDERED); 194 | } 195 | } 196 | -------------------------------------------------------------------------------- /java/util/Queue.java: -------------------------------------------------------------------------------- 1 | /* 2 | * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 3 | * 4 | * This code is free software; you can redistribute it and/or modify it 5 | * under the terms of the GNU General Public License version 2 only, as 6 | * published by the Free Software Foundation. Oracle designates this 7 | * particular file as subject to the "Classpath" exception as provided 8 | * by Oracle in the LICENSE file that accompanied this code. 9 | * 10 | * This code is distributed in the hope that it will be useful, but WITHOUT 11 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 12 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 13 | * version 2 for more details (a copy is included in the LICENSE file that 14 | * accompanied this code). 15 | * 16 | * You should have received a copy of the GNU General Public License version 17 | * 2 along with this work; if not, write to the Free Software Foundation, 18 | * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 19 | * 20 | * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 21 | * or visit www.oracle.com if you need additional information or have any 22 | * questions. 23 | */ 24 | 25 | /* 26 | * This file is available under and governed by the GNU General Public 27 | * License version 2 only, as published by the Free Software Foundation. 28 | * However, the following notice accompanied the original version of this 29 | * file: 30 | * 31 | * Written by Doug Lea with assistance from members of JCP JSR-166 32 | * Expert Group and released to the public domain, as explained at 33 | * http://creativecommons.org/publicdomain/zero/1.0/ 34 | */ 35 | 36 | package java.util; 37 | 38 | /** 39 | * A collection designed for holding elements prior to processing. 40 | * Besides basic {@link Collection} operations, queues provide 41 | * additional insertion, extraction, and inspection operations. 42 | * Each of these methods exists in two forms: one throws an exception 43 | * if the operation fails, the other returns a special value (either 44 | * {@code null} or {@code false}, depending on the operation). The 45 | * latter form of the insert operation is designed specifically for 46 | * use with capacity-restricted {@code Queue} implementations; in most 47 | * implementations, insert operations cannot fail. 48 | * 49 | * 50 | * 51 | * 52 | * 53 | * 54 | * 55 | * 56 | * 57 | * 58 | * 59 | * 60 | * 61 | * 62 | * 63 | * 64 | * 65 | * 66 | * 67 | * 68 | * 69 | * 70 | * 71 | * 72 | * 73 | * 74 | * 75 | *
Summary of Queue methods
Throws exceptionReturns special value
Insert{@link #add(Object) add(e)}{@link #offer(Object) offer(e)}
Remove{@link #remove() remove()}{@link #poll() poll()}
Examine{@link #element() element()}{@link #peek() peek()}
76 | * 77 | *

Queues typically, but do not necessarily, order elements in a 78 | * FIFO (first-in-first-out) manner. Among the exceptions are 79 | * priority queues, which order elements according to a supplied 80 | * comparator, or the elements' natural ordering, and LIFO queues (or 81 | * stacks) which order the elements LIFO (last-in-first-out). 82 | * Whatever the ordering used, the head of the queue is that 83 | * element which would be removed by a call to {@link #remove()} or 84 | * {@link #poll()}. In a FIFO queue, all new elements are inserted at 85 | * the tail of the queue. Other kinds of queues may use 86 | * different placement rules. Every {@code Queue} implementation 87 | * must specify its ordering properties. 88 | * 89 | *

The {@link #offer offer} method inserts an element if possible, 90 | * otherwise returning {@code false}. This differs from the {@link 91 | * java.util.Collection#add Collection.add} method, which can fail to 92 | * add an element only by throwing an unchecked exception. The 93 | * {@code offer} method is designed for use when failure is a normal, 94 | * rather than exceptional occurrence, for example, in fixed-capacity 95 | * (or "bounded") queues. 96 | * 97 | *

The {@link #remove()} and {@link #poll()} methods remove and 98 | * return the head of the queue. 99 | * Exactly which element is removed from the queue is a 100 | * function of the queue's ordering policy, which differs from 101 | * implementation to implementation. The {@code remove()} and 102 | * {@code poll()} methods differ only in their behavior when the 103 | * queue is empty: the {@code remove()} method throws an exception, 104 | * while the {@code poll()} method returns {@code null}. 105 | * 106 | *

The {@link #element()} and {@link #peek()} methods return, but do 107 | * not remove, the head of the queue. 108 | * 109 | *

The {@code Queue} interface does not define the blocking queue 110 | * methods, which are common in concurrent programming. These methods, 111 | * which wait for elements to appear or for space to become available, are 112 | * defined in the {@link java.util.concurrent.BlockingQueue} interface, which 113 | * extends this interface. 114 | * 115 | *

{@code Queue} implementations generally do not allow insertion 116 | * of {@code null} elements, although some implementations, such as 117 | * {@link LinkedList}, do not prohibit insertion of {@code null}. 118 | * Even in the implementations that permit it, {@code null} should 119 | * not be inserted into a {@code Queue}, as {@code null} is also 120 | * used as a special return value by the {@code poll} method to 121 | * indicate that the queue contains no elements. 122 | * 123 | *

{@code Queue} implementations generally do not define 124 | * element-based versions of methods {@code equals} and 125 | * {@code hashCode} but instead inherit the identity based versions 126 | * from class {@code Object}, because element-based equality is not 127 | * always well-defined for queues with the same elements but different 128 | * ordering properties. 129 | * 130 | *

This interface is a member of the 131 | * 132 | * Java Collections Framework. 133 | * 134 | * @since 1.5 135 | * @author Doug Lea 136 | * @param the type of elements held in this queue 137 | */ 138 | public interface Queue extends Collection { 139 | /** 140 | * Inserts the specified element into this queue if it is possible to do so 141 | * immediately without violating capacity restrictions, returning 142 | * {@code true} upon success and throwing an {@code IllegalStateException} 143 | * if no space is currently available. 144 | * 145 | * @param e the element to add 146 | * @return {@code true} (as specified by {@link Collection#add}) 147 | * @throws IllegalStateException if the element cannot be added at this 148 | * time due to capacity restrictions 149 | * @throws ClassCastException if the class of the specified element 150 | * prevents it from being added to this queue 151 | * @throws NullPointerException if the specified element is null and 152 | * this queue does not permit null elements 153 | * @throws IllegalArgumentException if some property of this element 154 | * prevents it from being added to this queue 155 | */ 156 | boolean add(E e); 157 | 158 | /** 159 | * Inserts the specified element into this queue if it is possible to do 160 | * so immediately without violating capacity restrictions. 161 | * When using a capacity-restricted queue, this method is generally 162 | * preferable to {@link #add}, which can fail to insert an element only 163 | * by throwing an exception. 164 | * 165 | * @param e the element to add 166 | * @return {@code true} if the element was added to this queue, else 167 | * {@code false} 168 | * @throws ClassCastException if the class of the specified element 169 | * prevents it from being added to this queue 170 | * @throws NullPointerException if the specified element is null and 171 | * this queue does not permit null elements 172 | * @throws IllegalArgumentException if some property of this element 173 | * prevents it from being added to this queue 174 | */ 175 | boolean offer(E e); 176 | 177 | /** 178 | * Retrieves and removes the head of this queue. This method differs 179 | * from {@link #poll() poll()} only in that it throws an exception if 180 | * this queue is empty. 181 | * 182 | * @return the head of this queue 183 | * @throws NoSuchElementException if this queue is empty 184 | */ 185 | E remove(); 186 | 187 | /** 188 | * Retrieves and removes the head of this queue, 189 | * or returns {@code null} if this queue is empty. 190 | * 191 | * @return the head of this queue, or {@code null} if this queue is empty 192 | */ 193 | E poll(); 194 | 195 | /** 196 | * Retrieves, but does not remove, the head of this queue. This method 197 | * differs from {@link #peek peek} only in that it throws an exception 198 | * if this queue is empty. 199 | * 200 | * @return the head of this queue 201 | * @throws NoSuchElementException if this queue is empty 202 | */ 203 | E element(); 204 | 205 | /** 206 | * Retrieves, but does not remove, the head of this queue, 207 | * or returns {@code null} if this queue is empty. 208 | * 209 | * @return the head of this queue, or {@code null} if this queue is empty 210 | */ 211 | E peek(); 212 | } 213 | -------------------------------------------------------------------------------- /java/util/RegularEnumSet.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2003, 2012, 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 | * Private implementation class for EnumSet, for "regular sized" enum types 30 | * (i.e., those with 64 or fewer enum constants). 31 | * 32 | * @author Josh Bloch 33 | * @since 1.5 34 | * @serial exclude 35 | */ 36 | class RegularEnumSet> extends EnumSet { 37 | private static final long serialVersionUID = 3411599620347842686L; 38 | /** 39 | * Bit vector representation of this set. The 2^k bit indicates the 40 | * presence of universe[k] in this set. 41 | */ 42 | private long elements = 0L; 43 | 44 | RegularEnumSet(ClasselementType, Enum[] universe) { 45 | super(elementType, universe); 46 | } 47 | 48 | void addRange(E from, E to) { 49 | elements = (-1L >>> (from.ordinal() - to.ordinal() - 1)) << from.ordinal(); 50 | } 51 | 52 | void addAll() { 53 | if (universe.length != 0) 54 | elements = -1L >>> -universe.length; 55 | } 56 | 57 | void complement() { 58 | if (universe.length != 0) { 59 | elements = ~elements; 60 | elements &= -1L >>> -universe.length; // Mask unused bits 61 | } 62 | } 63 | 64 | /** 65 | * Returns an iterator over the elements contained in this set. The 66 | * iterator traverses the elements in their natural order (which is 67 | * the order in which the enum constants are declared). The returned 68 | * Iterator is a "snapshot" iterator that will never throw {@link 69 | * ConcurrentModificationException}; the elements are traversed as they 70 | * existed when this call was invoked. 71 | * 72 | * @return an iterator over the elements contained in this set 73 | */ 74 | public Iterator iterator() { 75 | return new EnumSetIterator<>(); 76 | } 77 | 78 | private class EnumSetIterator> implements Iterator { 79 | /** 80 | * A bit vector representing the elements in the set not yet 81 | * returned by this iterator. 82 | */ 83 | long unseen; 84 | 85 | /** 86 | * The bit representing the last element returned by this iterator 87 | * but not removed, or zero if no such element exists. 88 | */ 89 | long lastReturned = 0; 90 | 91 | EnumSetIterator() { 92 | unseen = elements; 93 | } 94 | 95 | public boolean hasNext() { 96 | return unseen != 0; 97 | } 98 | 99 | @SuppressWarnings("unchecked") 100 | public E next() { 101 | if (unseen == 0) 102 | throw new NoSuchElementException(); 103 | lastReturned = unseen & -unseen; 104 | unseen -= lastReturned; 105 | return (E) universe[Long.numberOfTrailingZeros(lastReturned)]; 106 | } 107 | 108 | public void remove() { 109 | if (lastReturned == 0) 110 | throw new IllegalStateException(); 111 | elements &= ~lastReturned; 112 | lastReturned = 0; 113 | } 114 | } 115 | 116 | /** 117 | * Returns the number of elements in this set. 118 | * 119 | * @return the number of elements in this set 120 | */ 121 | public int size() { 122 | return Long.bitCount(elements); 123 | } 124 | 125 | /** 126 | * Returns {@code true} if this set contains no elements. 127 | * 128 | * @return {@code true} if this set contains no elements 129 | */ 130 | public boolean isEmpty() { 131 | return elements == 0; 132 | } 133 | 134 | /** 135 | * Returns {@code true} if this set contains the specified element. 136 | * 137 | * @param e element to be checked for containment in this collection 138 | * @return {@code true} if this set contains the specified element 139 | */ 140 | public boolean contains(Object e) { 141 | if (e == null) 142 | return false; 143 | Class eClass = e.getClass(); 144 | if (eClass != elementType && eClass.getSuperclass() != elementType) 145 | return false; 146 | 147 | return (elements & (1L << ((Enum)e).ordinal())) != 0; 148 | } 149 | 150 | // Modification Operations 151 | 152 | /** 153 | * Adds the specified element to this set if it is not already present. 154 | * 155 | * @param e element to be added to this set 156 | * @return {@code true} if the set changed as a result of the call 157 | * 158 | * @throws NullPointerException if {@code e} is null 159 | */ 160 | public boolean add(E e) { 161 | typeCheck(e); 162 | 163 | long oldElements = elements; 164 | elements |= (1L << ((Enum)e).ordinal()); 165 | return elements != oldElements; 166 | } 167 | 168 | /** 169 | * Removes the specified element from this set if it is present. 170 | * 171 | * @param e element to be removed from this set, if present 172 | * @return {@code true} if the set contained the specified element 173 | */ 174 | public boolean remove(Object e) { 175 | if (e == null) 176 | return false; 177 | Class eClass = e.getClass(); 178 | if (eClass != elementType && eClass.getSuperclass() != elementType) 179 | return false; 180 | 181 | long oldElements = elements; 182 | elements &= ~(1L << ((Enum)e).ordinal()); 183 | return elements != oldElements; 184 | } 185 | 186 | // Bulk Operations 187 | 188 | /** 189 | * Returns {@code true} if this set contains all of the elements 190 | * in the specified collection. 191 | * 192 | * @param c collection to be checked for containment in this set 193 | * @return {@code true} if this set contains all of the elements 194 | * in the specified collection 195 | * @throws NullPointerException if the specified collection is null 196 | */ 197 | public boolean containsAll(Collection c) { 198 | if (!(c instanceof RegularEnumSet)) 199 | return super.containsAll(c); 200 | 201 | RegularEnumSet es = (RegularEnumSet)c; 202 | if (es.elementType != elementType) 203 | return es.isEmpty(); 204 | 205 | return (es.elements & ~elements) == 0; 206 | } 207 | 208 | /** 209 | * Adds all of the elements in the specified collection to this set. 210 | * 211 | * @param c collection whose elements are to be added to this set 212 | * @return {@code true} if this set changed as a result of the call 213 | * @throws NullPointerException if the specified collection or any 214 | * of its elements are null 215 | */ 216 | public boolean addAll(Collection c) { 217 | if (!(c instanceof RegularEnumSet)) 218 | return super.addAll(c); 219 | 220 | RegularEnumSet es = (RegularEnumSet)c; 221 | if (es.elementType != elementType) { 222 | if (es.isEmpty()) 223 | return false; 224 | else 225 | throw new ClassCastException( 226 | es.elementType + " != " + elementType); 227 | } 228 | 229 | long oldElements = elements; 230 | elements |= es.elements; 231 | return elements != oldElements; 232 | } 233 | 234 | /** 235 | * Removes from this set all of its elements that are contained in 236 | * the specified collection. 237 | * 238 | * @param c elements to be removed from this set 239 | * @return {@code true} if this set changed as a result of the call 240 | * @throws NullPointerException if the specified collection is null 241 | */ 242 | public boolean removeAll(Collection c) { 243 | if (!(c instanceof RegularEnumSet)) 244 | return super.removeAll(c); 245 | 246 | RegularEnumSet es = (RegularEnumSet)c; 247 | if (es.elementType != elementType) 248 | return false; 249 | 250 | long oldElements = elements; 251 | elements &= ~es.elements; 252 | return elements != oldElements; 253 | } 254 | 255 | /** 256 | * Retains only the elements in this set that are contained in the 257 | * specified collection. 258 | * 259 | * @param c elements to be retained in this set 260 | * @return {@code true} if this set changed as a result of the call 261 | * @throws NullPointerException if the specified collection is null 262 | */ 263 | public boolean retainAll(Collection c) { 264 | if (!(c instanceof RegularEnumSet)) 265 | return super.retainAll(c); 266 | 267 | RegularEnumSet es = (RegularEnumSet)c; 268 | if (es.elementType != elementType) { 269 | boolean changed = (elements != 0); 270 | elements = 0; 271 | return changed; 272 | } 273 | 274 | long oldElements = elements; 275 | elements &= es.elements; 276 | return elements != oldElements; 277 | } 278 | 279 | /** 280 | * Removes all of the elements from this set. 281 | */ 282 | public void clear() { 283 | elements = 0; 284 | } 285 | 286 | /** 287 | * Compares the specified object with this set for equality. Returns 288 | * {@code true} if the given object is also a set, the two sets have 289 | * the same size, and every member of the given set is contained in 290 | * this set. 291 | * 292 | * @param o object to be compared for equality with this set 293 | * @return {@code true} if the specified object is equal to this set 294 | */ 295 | public boolean equals(Object o) { 296 | if (!(o instanceof RegularEnumSet)) 297 | return super.equals(o); 298 | 299 | RegularEnumSet es = (RegularEnumSet)o; 300 | if (es.elementType != elementType) 301 | return elements == 0 && es.elements == 0; 302 | return es.elements == elements; 303 | } 304 | } 305 | -------------------------------------------------------------------------------- /java/util/AbstractSequentialList.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 1997, 2018, 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 | * This class provides a skeletal implementation of the {@code List} 30 | * interface to minimize the effort required to implement this interface 31 | * backed by a "sequential access" data store (such as a linked list). For 32 | * random access data (such as an array), {@code AbstractList} should be used 33 | * in preference to this class.

34 | * 35 | * This class is the opposite of the {@code AbstractList} class in the sense 36 | * that it implements the "random access" methods ({@code get(int index)}, 37 | * {@code set(int index, E element)}, {@code add(int index, E element)} and 38 | * {@code remove(int index)}) on top of the list's list iterator, instead of 39 | * the other way around.

40 | * 41 | * To implement a list the programmer needs only to extend this class and 42 | * provide implementations for the {@code listIterator} and {@code size} 43 | * methods. For an unmodifiable list, the programmer need only implement the 44 | * list iterator's {@code hasNext}, {@code next}, {@code hasPrevious}, 45 | * {@code previous} and {@code index} methods.

46 | * 47 | * For a modifiable list the programmer should additionally implement the list 48 | * iterator's {@code set} method. For a variable-size list the programmer 49 | * should additionally implement the list iterator's {@code remove} and 50 | * {@code add} methods.

51 | * 52 | * The programmer should generally provide a void (no argument) and collection 53 | * constructor, as per the recommendation in the {@code Collection} interface 54 | * specification.

55 | * 56 | * This class is a member of the 57 | * 58 | * Java Collections Framework. 59 | * 60 | * @author Josh Bloch 61 | * @author Neal Gafter 62 | * @see Collection 63 | * @see List 64 | * @see AbstractList 65 | * @see AbstractCollection 66 | * @since 1.2 67 | */ 68 | 69 | public abstract class AbstractSequentialList extends AbstractList { 70 | /** 71 | * Sole constructor. (For invocation by subclass constructors, typically 72 | * implicit.) 73 | */ 74 | protected AbstractSequentialList() { 75 | } 76 | 77 | /** 78 | * Returns the element at the specified position in this list. 79 | * 80 | *

This implementation first gets a list iterator pointing to the 81 | * indexed element (with {@code listIterator(index)}). Then, it gets 82 | * the element using {@code ListIterator.next} and returns it. 83 | * 84 | * @throws IndexOutOfBoundsException {@inheritDoc} 85 | */ 86 | public E get(int index) { 87 | try { 88 | return listIterator(index).next(); 89 | } catch (NoSuchElementException exc) { 90 | throw new IndexOutOfBoundsException("Index: "+index); 91 | } 92 | } 93 | 94 | /** 95 | * Replaces the element at the specified position in this list with the 96 | * specified element (optional operation). 97 | * 98 | *

This implementation first gets a list iterator pointing to the 99 | * indexed element (with {@code listIterator(index)}). Then, it gets 100 | * the current element using {@code ListIterator.next} and replaces it 101 | * with {@code ListIterator.set}. 102 | * 103 | *

Note that this implementation will throw an 104 | * {@code UnsupportedOperationException} if the list iterator does not 105 | * implement the {@code set} operation. 106 | * 107 | * @throws UnsupportedOperationException {@inheritDoc} 108 | * @throws ClassCastException {@inheritDoc} 109 | * @throws NullPointerException {@inheritDoc} 110 | * @throws IllegalArgumentException {@inheritDoc} 111 | * @throws IndexOutOfBoundsException {@inheritDoc} 112 | */ 113 | public E set(int index, E element) { 114 | try { 115 | ListIterator e = listIterator(index); 116 | E oldVal = e.next(); 117 | e.set(element); 118 | return oldVal; 119 | } catch (NoSuchElementException exc) { 120 | throw new IndexOutOfBoundsException("Index: "+index); 121 | } 122 | } 123 | 124 | /** 125 | * Inserts the specified element at the specified position in this list 126 | * (optional operation). Shifts the element currently at that position 127 | * (if any) and any subsequent elements to the right (adds one to their 128 | * indices). 129 | * 130 | *

This implementation first gets a list iterator pointing to the 131 | * indexed element (with {@code listIterator(index)}). Then, it 132 | * inserts the specified element with {@code ListIterator.add}. 133 | * 134 | *

Note that this implementation will throw an 135 | * {@code UnsupportedOperationException} if the list iterator does not 136 | * implement the {@code add} operation. 137 | * 138 | * @throws UnsupportedOperationException {@inheritDoc} 139 | * @throws ClassCastException {@inheritDoc} 140 | * @throws NullPointerException {@inheritDoc} 141 | * @throws IllegalArgumentException {@inheritDoc} 142 | * @throws IndexOutOfBoundsException {@inheritDoc} 143 | */ 144 | public void add(int index, E element) { 145 | try { 146 | listIterator(index).add(element); 147 | } catch (NoSuchElementException exc) { 148 | throw new IndexOutOfBoundsException("Index: "+index); 149 | } 150 | } 151 | 152 | /** 153 | * Removes the element at the specified position in this list (optional 154 | * operation). Shifts any subsequent elements to the left (subtracts one 155 | * from their indices). Returns the element that was removed from the 156 | * list. 157 | * 158 | *

This implementation first gets a list iterator pointing to the 159 | * indexed element (with {@code listIterator(index)}). Then, it removes 160 | * the element with {@code ListIterator.remove}. 161 | * 162 | *

Note that this implementation will throw an 163 | * {@code UnsupportedOperationException} if the list iterator does not 164 | * implement the {@code remove} operation. 165 | * 166 | * @throws UnsupportedOperationException {@inheritDoc} 167 | * @throws IndexOutOfBoundsException {@inheritDoc} 168 | */ 169 | public E remove(int index) { 170 | try { 171 | ListIterator e = listIterator(index); 172 | E outCast = e.next(); 173 | e.remove(); 174 | return outCast; 175 | } catch (NoSuchElementException exc) { 176 | throw new IndexOutOfBoundsException("Index: "+index); 177 | } 178 | } 179 | 180 | 181 | // Bulk Operations 182 | 183 | /** 184 | * Inserts all of the elements in the specified collection into this 185 | * list at the specified position (optional operation). Shifts the 186 | * element currently at that position (if any) and any subsequent 187 | * elements to the right (increases their indices). The new elements 188 | * will appear in this list in the order that they are returned by the 189 | * specified collection's iterator. The behavior of this operation is 190 | * undefined if the specified collection is modified while the 191 | * operation is in progress. (Note that this will occur if the specified 192 | * collection is this list, and it's nonempty.) 193 | * 194 | *

This implementation gets an iterator over the specified collection and 195 | * a list iterator over this list pointing to the indexed element (with 196 | * {@code listIterator(index)}). Then, it iterates over the specified 197 | * collection, inserting the elements obtained from the iterator into this 198 | * list, one at a time, using {@code ListIterator.add} followed by 199 | * {@code ListIterator.next} (to skip over the added element). 200 | * 201 | *

Note that this implementation will throw an 202 | * {@code UnsupportedOperationException} if the list iterator returned by 203 | * the {@code listIterator} method does not implement the {@code add} 204 | * operation. 205 | * 206 | * @throws UnsupportedOperationException {@inheritDoc} 207 | * @throws ClassCastException {@inheritDoc} 208 | * @throws NullPointerException {@inheritDoc} 209 | * @throws IllegalArgumentException {@inheritDoc} 210 | * @throws IndexOutOfBoundsException {@inheritDoc} 211 | */ 212 | public boolean addAll(int index, Collection c) { 213 | try { 214 | boolean modified = false; 215 | ListIterator e1 = listIterator(index); 216 | for (E e : c) { 217 | e1.add(e); 218 | modified = true; 219 | } 220 | return modified; 221 | } catch (NoSuchElementException exc) { 222 | throw new IndexOutOfBoundsException("Index: "+index); 223 | } 224 | } 225 | 226 | 227 | // Iterators 228 | 229 | /** 230 | * Returns an iterator over the elements in this list (in proper 231 | * sequence).

232 | * 233 | * This implementation merely returns a list iterator over the list. 234 | * 235 | * @return an iterator over the elements in this list (in proper sequence) 236 | */ 237 | public Iterator iterator() { 238 | return listIterator(); 239 | } 240 | 241 | /** 242 | * Returns a list iterator over the elements in this list (in proper 243 | * sequence). 244 | * 245 | * @param index index of first element to be returned from the list 246 | * iterator (by a call to the {@code next} method) 247 | * @return a list iterator over the elements in this list (in proper 248 | * sequence) 249 | * @throws IndexOutOfBoundsException {@inheritDoc} 250 | */ 251 | public abstract ListIterator listIterator(int index); 252 | } 253 | -------------------------------------------------------------------------------- /java/util/PrimitiveIterator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2013, 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 | package java.util; 26 | 27 | import java.util.function.Consumer; 28 | import java.util.function.DoubleConsumer; 29 | import java.util.function.IntConsumer; 30 | import java.util.function.LongConsumer; 31 | 32 | /** 33 | * A base type for primitive specializations of {@code Iterator}. Specialized 34 | * subtypes are provided for {@link OfInt int}, {@link OfLong long}, and 35 | * {@link OfDouble double} values. 36 | * 37 | *

The specialized subtype default implementations of {@link Iterator#next} 38 | * and {@link Iterator#forEachRemaining(java.util.function.Consumer)} box 39 | * primitive values to instances of their corresponding wrapper class. Such 40 | * boxing may offset any advantages gained when using the primitive 41 | * specializations. To avoid boxing, the corresponding primitive-based methods 42 | * should be used. For example, {@link PrimitiveIterator.OfInt#nextInt()} and 43 | * {@link PrimitiveIterator.OfInt#forEachRemaining(java.util.function.IntConsumer)} 44 | * should be used in preference to {@link PrimitiveIterator.OfInt#next()} and 45 | * {@link PrimitiveIterator.OfInt#forEachRemaining(java.util.function.Consumer)}. 46 | * 47 | *

Iteration of primitive values using boxing-based methods 48 | * {@link Iterator#next next()} and 49 | * {@link Iterator#forEachRemaining(java.util.function.Consumer) forEachRemaining()}, 50 | * does not affect the order in which the values, transformed to boxed values, 51 | * are encountered. 52 | * 53 | * @implNote 54 | * If the boolean system property {@code org.openjdk.java.util.stream.tripwire} 55 | * is set to {@code true} then diagnostic warnings are reported if boxing of 56 | * primitive values occur when operating on primitive subtype specializations. 57 | * 58 | * @param the type of elements returned by this PrimitiveIterator. The 59 | * type must be a wrapper type for a primitive type, such as 60 | * {@code Integer} for the primitive {@code int} type. 61 | * @param the type of primitive consumer. The type must be a 62 | * primitive specialization of {@link java.util.function.Consumer} for 63 | * {@code T}, such as {@link java.util.function.IntConsumer} for 64 | * {@code Integer}. 65 | * 66 | * @since 1.8 67 | */ 68 | public interface PrimitiveIterator extends Iterator { 69 | 70 | /** 71 | * Performs the given action for each remaining element, in the order 72 | * elements occur when iterating, until all elements have been processed 73 | * or the action throws an exception. Errors or runtime exceptions 74 | * thrown by the action are relayed to the caller. 75 | * 76 | * @param action The action to be performed for each element 77 | * @throws NullPointerException if the specified action is null 78 | */ 79 | @SuppressWarnings("overloads") 80 | void forEachRemaining(T_CONS action); 81 | 82 | /** 83 | * An Iterator specialized for {@code int} values. 84 | * @since 1.8 85 | */ 86 | public static interface OfInt extends PrimitiveIterator { 87 | 88 | /** 89 | * Returns the next {@code int} element in the iteration. 90 | * 91 | * @return the next {@code int} element in the iteration 92 | * @throws NoSuchElementException if the iteration has no more elements 93 | */ 94 | int nextInt(); 95 | 96 | /** 97 | * Performs the given action for each remaining element until all elements 98 | * have been processed or the action throws an exception. Actions are 99 | * performed in the order of iteration, if that order is specified. 100 | * Exceptions thrown by the action are relayed to the caller. 101 | * 102 | * @implSpec 103 | *

The default implementation behaves as if: 104 | *

{@code
105 |          *     while (hasNext())
106 |          *         action.accept(nextInt());
107 |          * }
108 | * 109 | * @param action The action to be performed for each element 110 | * @throws NullPointerException if the specified action is null 111 | */ 112 | default void forEachRemaining(IntConsumer action) { 113 | Objects.requireNonNull(action); 114 | while (hasNext()) 115 | action.accept(nextInt()); 116 | } 117 | 118 | /** 119 | * {@inheritDoc} 120 | * @implSpec 121 | * The default implementation boxes the result of calling 122 | * {@link #nextInt()}, and returns that boxed result. 123 | */ 124 | @Override 125 | default Integer next() { 126 | if (Tripwire.ENABLED) 127 | Tripwire.trip(getClass(), "{0} calling PrimitiveIterator.OfInt.nextInt()"); 128 | return nextInt(); 129 | } 130 | 131 | /** 132 | * {@inheritDoc} 133 | * @implSpec 134 | * If the action is an instance of {@code IntConsumer} then it is cast 135 | * to {@code IntConsumer} and passed to {@link #forEachRemaining}; 136 | * otherwise the action is adapted to an instance of 137 | * {@code IntConsumer}, by boxing the argument of {@code IntConsumer}, 138 | * and then passed to {@link #forEachRemaining}. 139 | */ 140 | @Override 141 | default void forEachRemaining(Consumer action) { 142 | if (action instanceof IntConsumer) { 143 | forEachRemaining((IntConsumer) action); 144 | } 145 | else { 146 | // The method reference action::accept is never null 147 | Objects.requireNonNull(action); 148 | if (Tripwire.ENABLED) 149 | Tripwire.trip(getClass(), "{0} calling PrimitiveIterator.OfInt.forEachRemainingInt(action::accept)"); 150 | forEachRemaining((IntConsumer) action::accept); 151 | } 152 | } 153 | 154 | } 155 | 156 | /** 157 | * An Iterator specialized for {@code long} values. 158 | * @since 1.8 159 | */ 160 | public static interface OfLong extends PrimitiveIterator { 161 | 162 | /** 163 | * Returns the next {@code long} element in the iteration. 164 | * 165 | * @return the next {@code long} element in the iteration 166 | * @throws NoSuchElementException if the iteration has no more elements 167 | */ 168 | long nextLong(); 169 | 170 | /** 171 | * Performs the given action for each remaining element until all elements 172 | * have been processed or the action throws an exception. Actions are 173 | * performed in the order of iteration, if that order is specified. 174 | * Exceptions thrown by the action are relayed to the caller. 175 | * 176 | * @implSpec 177 | *

The default implementation behaves as if: 178 | *

{@code
179 |          *     while (hasNext())
180 |          *         action.accept(nextLong());
181 |          * }
182 | * 183 | * @param action The action to be performed for each element 184 | * @throws NullPointerException if the specified action is null 185 | */ 186 | default void forEachRemaining(LongConsumer action) { 187 | Objects.requireNonNull(action); 188 | while (hasNext()) 189 | action.accept(nextLong()); 190 | } 191 | 192 | /** 193 | * {@inheritDoc} 194 | * @implSpec 195 | * The default implementation boxes the result of calling 196 | * {@link #nextLong()}, and returns that boxed result. 197 | */ 198 | @Override 199 | default Long next() { 200 | if (Tripwire.ENABLED) 201 | Tripwire.trip(getClass(), "{0} calling PrimitiveIterator.OfLong.nextLong()"); 202 | return nextLong(); 203 | } 204 | 205 | /** 206 | * {@inheritDoc} 207 | * @implSpec 208 | * If the action is an instance of {@code LongConsumer} then it is cast 209 | * to {@code LongConsumer} and passed to {@link #forEachRemaining}; 210 | * otherwise the action is adapted to an instance of 211 | * {@code LongConsumer}, by boxing the argument of {@code LongConsumer}, 212 | * and then passed to {@link #forEachRemaining}. 213 | */ 214 | @Override 215 | default void forEachRemaining(Consumer action) { 216 | if (action instanceof LongConsumer) { 217 | forEachRemaining((LongConsumer) action); 218 | } 219 | else { 220 | // The method reference action::accept is never null 221 | Objects.requireNonNull(action); 222 | if (Tripwire.ENABLED) 223 | Tripwire.trip(getClass(), "{0} calling PrimitiveIterator.OfLong.forEachRemainingLong(action::accept)"); 224 | forEachRemaining((LongConsumer) action::accept); 225 | } 226 | } 227 | } 228 | 229 | /** 230 | * An Iterator specialized for {@code double} values. 231 | * @since 1.8 232 | */ 233 | public static interface OfDouble extends PrimitiveIterator { 234 | 235 | /** 236 | * Returns the next {@code double} element in the iteration. 237 | * 238 | * @return the next {@code double} element in the iteration 239 | * @throws NoSuchElementException if the iteration has no more elements 240 | */ 241 | double nextDouble(); 242 | 243 | /** 244 | * Performs the given action for each remaining element until all elements 245 | * have been processed or the action throws an exception. Actions are 246 | * performed in the order of iteration, if that order is specified. 247 | * Exceptions thrown by the action are relayed to the caller. 248 | * 249 | * @implSpec 250 | *

The default implementation behaves as if: 251 | *

{@code
252 |          *     while (hasNext())
253 |          *         action.accept(nextDouble());
254 |          * }
255 | * 256 | * @param action The action to be performed for each element 257 | * @throws NullPointerException if the specified action is null 258 | */ 259 | default void forEachRemaining(DoubleConsumer action) { 260 | Objects.requireNonNull(action); 261 | while (hasNext()) 262 | action.accept(nextDouble()); 263 | } 264 | 265 | /** 266 | * {@inheritDoc} 267 | * @implSpec 268 | * The default implementation boxes the result of calling 269 | * {@link #nextDouble()}, and returns that boxed result. 270 | */ 271 | @Override 272 | default Double next() { 273 | if (Tripwire.ENABLED) 274 | Tripwire.trip(getClass(), "{0} calling PrimitiveIterator.OfDouble.nextLong()"); 275 | return nextDouble(); 276 | } 277 | 278 | /** 279 | * {@inheritDoc} 280 | * @implSpec 281 | * If the action is an instance of {@code DoubleConsumer} then it is 282 | * cast to {@code DoubleConsumer} and passed to 283 | * {@link #forEachRemaining}; otherwise the action is adapted to 284 | * an instance of {@code DoubleConsumer}, by boxing the argument of 285 | * {@code DoubleConsumer}, and then passed to 286 | * {@link #forEachRemaining}. 287 | */ 288 | @Override 289 | default void forEachRemaining(Consumer action) { 290 | if (action instanceof DoubleConsumer) { 291 | forEachRemaining((DoubleConsumer) action); 292 | } 293 | else { 294 | // The method reference action::accept is never null 295 | Objects.requireNonNull(action); 296 | if (Tripwire.ENABLED) 297 | Tripwire.trip(getClass(), "{0} calling PrimitiveIterator.OfDouble.forEachRemainingDouble(action::accept)"); 298 | forEachRemaining((DoubleConsumer) action::accept); 299 | } 300 | } 301 | } 302 | } 303 | -------------------------------------------------------------------------------- /java/util/SortedSet.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 1998, 2018, 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 | * A {@link Set} that further provides a total ordering on its elements. 30 | * The elements are ordered using their {@linkplain Comparable natural 31 | * ordering}, or by a {@link Comparator} typically provided at sorted 32 | * set creation time. The set's iterator will traverse the set in 33 | * ascending element order. Several additional operations are provided 34 | * to take advantage of the ordering. (This interface is the set 35 | * analogue of {@link SortedMap}.) 36 | * 37 | *

All elements inserted into a sorted set must implement the {@code Comparable} 38 | * interface (or be accepted by the specified comparator). Furthermore, all 39 | * such elements must be mutually comparable: {@code e1.compareTo(e2)} 40 | * (or {@code comparator.compare(e1, e2)}) must not throw a 41 | * {@code ClassCastException} for any elements {@code e1} and {@code e2} in 42 | * the sorted set. Attempts to violate this restriction will cause the 43 | * offending method or constructor invocation to throw a 44 | * {@code ClassCastException}. 45 | * 46 | *

Note that the ordering maintained by a sorted set (whether or not an 47 | * explicit comparator is provided) must be consistent with equals if 48 | * the sorted set is to correctly implement the {@code Set} interface. (See 49 | * the {@code Comparable} interface or {@code Comparator} interface for a 50 | * precise definition of consistent with equals.) This is so because 51 | * the {@code Set} interface is defined in terms of the {@code equals} 52 | * operation, but a sorted set performs all element comparisons using its 53 | * {@code compareTo} (or {@code compare}) method, so two elements that are 54 | * deemed equal by this method are, from the standpoint of the sorted set, 55 | * equal. The behavior of a sorted set is well-defined even if its 56 | * ordering is inconsistent with equals; it just fails to obey the general 57 | * contract of the {@code Set} interface. 58 | * 59 | *

All general-purpose sorted set implementation classes should 60 | * provide four "standard" constructors: 1) A void (no arguments) 61 | * constructor, which creates an empty sorted set sorted according to 62 | * the natural ordering of its elements. 2) A constructor with a 63 | * single argument of type {@code Comparator}, which creates an empty 64 | * sorted set sorted according to the specified comparator. 3) A 65 | * constructor with a single argument of type {@code Collection}, 66 | * which creates a new sorted set with the same elements as its 67 | * argument, sorted according to the natural ordering of the elements. 68 | * 4) A constructor with a single argument of type {@code SortedSet}, 69 | * which creates a new sorted set with the same elements and the same 70 | * ordering as the input sorted set. There is no way to enforce this 71 | * recommendation, as interfaces cannot contain constructors. 72 | * 73 | *

Note: several methods return subsets with restricted ranges. 74 | * Such ranges are half-open, that is, they include their low 75 | * endpoint but not their high endpoint (where applicable). 76 | * If you need a closed range (which includes both endpoints), and 77 | * the element type allows for calculation of the successor of a given 78 | * value, merely request the subrange from {@code lowEndpoint} to 79 | * {@code successor(highEndpoint)}. For example, suppose that {@code s} 80 | * is a sorted set of strings. The following idiom obtains a view 81 | * containing all of the strings in {@code s} from {@code low} to 82 | * {@code high}, inclusive:

 83 |  *   SortedSet<String> sub = s.subSet(low, high+"\0");
84 | * 85 | * A similar technique can be used to generate an open range (which 86 | * contains neither endpoint). The following idiom obtains a view 87 | * containing all of the Strings in {@code s} from {@code low} to 88 | * {@code high}, exclusive:
 89 |  *   SortedSet<String> sub = s.subSet(low+"\0", high);
90 | * 91 | *

This interface is a member of the 92 | * 93 | * Java Collections Framework. 94 | * 95 | * @param the type of elements maintained by this set 96 | * 97 | * @author Josh Bloch 98 | * @see Set 99 | * @see TreeSet 100 | * @see SortedMap 101 | * @see Collection 102 | * @see Comparable 103 | * @see Comparator 104 | * @see ClassCastException 105 | * @since 1.2 106 | */ 107 | 108 | public interface SortedSet extends Set { 109 | /** 110 | * Returns the comparator used to order the elements in this set, 111 | * or {@code null} if this set uses the {@linkplain Comparable 112 | * natural ordering} of its elements. 113 | * 114 | * @return the comparator used to order the elements in this set, 115 | * or {@code null} if this set uses the natural ordering 116 | * of its elements 117 | */ 118 | Comparator comparator(); 119 | 120 | /** 121 | * Returns a view of the portion of this set whose elements range 122 | * from {@code fromElement}, inclusive, to {@code toElement}, 123 | * exclusive. (If {@code fromElement} and {@code toElement} are 124 | * equal, the returned set is empty.) The returned set is backed 125 | * by this set, so changes in the returned set are reflected in 126 | * this set, and vice-versa. The returned set supports all 127 | * optional set operations that this set supports. 128 | * 129 | *

The returned set will throw an {@code IllegalArgumentException} 130 | * on an attempt to insert an element outside its range. 131 | * 132 | * @param fromElement low endpoint (inclusive) of the returned set 133 | * @param toElement high endpoint (exclusive) of the returned set 134 | * @return a view of the portion of this set whose elements range from 135 | * {@code fromElement}, inclusive, to {@code toElement}, exclusive 136 | * @throws ClassCastException if {@code fromElement} and 137 | * {@code toElement} cannot be compared to one another using this 138 | * set's comparator (or, if the set has no comparator, using 139 | * natural ordering). Implementations may, but are not required 140 | * to, throw this exception if {@code fromElement} or 141 | * {@code toElement} cannot be compared to elements currently in 142 | * the set. 143 | * @throws NullPointerException if {@code fromElement} or 144 | * {@code toElement} is null and this set does not permit null 145 | * elements 146 | * @throws IllegalArgumentException if {@code fromElement} is 147 | * greater than {@code toElement}; or if this set itself 148 | * has a restricted range, and {@code fromElement} or 149 | * {@code toElement} lies outside the bounds of the range 150 | */ 151 | SortedSet subSet(E fromElement, E toElement); 152 | 153 | /** 154 | * Returns a view of the portion of this set whose elements are 155 | * strictly less than {@code toElement}. The returned set is 156 | * backed by this set, so changes in the returned set are 157 | * reflected in this set, and vice-versa. The returned set 158 | * supports all optional set operations that this set supports. 159 | * 160 | *

The returned set will throw an {@code IllegalArgumentException} 161 | * on an attempt to insert an element outside its range. 162 | * 163 | * @param toElement high endpoint (exclusive) of the returned set 164 | * @return a view of the portion of this set whose elements are strictly 165 | * less than {@code toElement} 166 | * @throws ClassCastException if {@code toElement} is not compatible 167 | * with this set's comparator (or, if the set has no comparator, 168 | * if {@code toElement} does not implement {@link Comparable}). 169 | * Implementations may, but are not required to, throw this 170 | * exception if {@code toElement} cannot be compared to elements 171 | * currently in the set. 172 | * @throws NullPointerException if {@code toElement} is null and 173 | * this set does not permit null elements 174 | * @throws IllegalArgumentException if this set itself has a 175 | * restricted range, and {@code toElement} lies outside the 176 | * bounds of the range 177 | */ 178 | SortedSet headSet(E toElement); 179 | 180 | /** 181 | * Returns a view of the portion of this set whose elements are 182 | * greater than or equal to {@code fromElement}. The returned 183 | * set is backed by this set, so changes in the returned set are 184 | * reflected in this set, and vice-versa. The returned set 185 | * supports all optional set operations that this set supports. 186 | * 187 | *

The returned set will throw an {@code IllegalArgumentException} 188 | * on an attempt to insert an element outside its range. 189 | * 190 | * @param fromElement low endpoint (inclusive) of the returned set 191 | * @return a view of the portion of this set whose elements are greater 192 | * than or equal to {@code fromElement} 193 | * @throws ClassCastException if {@code fromElement} is not compatible 194 | * with this set's comparator (or, if the set has no comparator, 195 | * if {@code fromElement} does not implement {@link Comparable}). 196 | * Implementations may, but are not required to, throw this 197 | * exception if {@code fromElement} cannot be compared to elements 198 | * currently in the set. 199 | * @throws NullPointerException if {@code fromElement} is null 200 | * and this set does not permit null elements 201 | * @throws IllegalArgumentException if this set itself has a 202 | * restricted range, and {@code fromElement} lies outside the 203 | * bounds of the range 204 | */ 205 | SortedSet tailSet(E fromElement); 206 | 207 | /** 208 | * Returns the first (lowest) element currently in this set. 209 | * 210 | * @return the first (lowest) element currently in this set 211 | * @throws NoSuchElementException if this set is empty 212 | */ 213 | E first(); 214 | 215 | /** 216 | * Returns the last (highest) element currently in this set. 217 | * 218 | * @return the last (highest) element currently in this set 219 | * @throws NoSuchElementException if this set is empty 220 | */ 221 | E last(); 222 | 223 | /** 224 | * Creates a {@code Spliterator} over the elements in this sorted set. 225 | * 226 | *

The {@code Spliterator} reports {@link Spliterator#DISTINCT}, 227 | * {@link Spliterator#SORTED} and {@link Spliterator#ORDERED}. 228 | * Implementations should document the reporting of additional 229 | * characteristic values. 230 | * 231 | *

The spliterator's comparator (see 232 | * {@link java.util.Spliterator#getComparator()}) must be {@code null} if 233 | * the sorted set's comparator (see {@link #comparator()}) is {@code null}. 234 | * Otherwise, the spliterator's comparator must be the same as or impose the 235 | * same total ordering as the sorted set's comparator. 236 | * 237 | * @implSpec 238 | * The default implementation creates a 239 | * late-binding spliterator 240 | * from the sorted set's {@code Iterator}. The spliterator inherits the 241 | * fail-fast properties of the set's iterator. The 242 | * spliterator's comparator is the same as the sorted set's comparator. 243 | *

244 | * The created {@code Spliterator} additionally reports 245 | * {@link Spliterator#SIZED}. 246 | * 247 | * @implNote 248 | * The created {@code Spliterator} additionally reports 249 | * {@link Spliterator#SUBSIZED}. 250 | * 251 | * @return a {@code Spliterator} over the elements in this sorted set 252 | * @since 1.8 253 | */ 254 | @Override 255 | default Spliterator spliterator() { 256 | return new Spliterators.IteratorSpliterator( 257 | this, Spliterator.DISTINCT | Spliterator.SORTED | Spliterator.ORDERED) { 258 | @Override 259 | public Comparator getComparator() { 260 | return SortedSet.this.comparator(); 261 | } 262 | }; 263 | } 264 | } 265 | -------------------------------------------------------------------------------- /java/util/JumboEnumSet.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2003, 2012, 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 | * Private implementation class for EnumSet, for "jumbo" enum types 30 | * (i.e., those with more than 64 elements). 31 | * 32 | * @author Josh Bloch 33 | * @since 1.5 34 | * @serial exclude 35 | */ 36 | class JumboEnumSet> extends EnumSet { 37 | private static final long serialVersionUID = 334349849919042784L; 38 | 39 | /** 40 | * Bit vector representation of this set. The ith bit of the jth 41 | * element of this array represents the presence of universe[64*j +i] 42 | * in this set. 43 | */ 44 | private long elements[]; 45 | 46 | // Redundant - maintained for performance 47 | private int size = 0; 48 | 49 | JumboEnumSet(ClasselementType, Enum[] universe) { 50 | super(elementType, universe); 51 | elements = new long[(universe.length + 63) >>> 6]; 52 | } 53 | 54 | void addRange(E from, E to) { 55 | int fromIndex = from.ordinal() >>> 6; 56 | int toIndex = to.ordinal() >>> 6; 57 | 58 | if (fromIndex == toIndex) { 59 | elements[fromIndex] = (-1L >>> (from.ordinal() - to.ordinal() - 1)) 60 | << from.ordinal(); 61 | } else { 62 | elements[fromIndex] = (-1L << from.ordinal()); 63 | for (int i = fromIndex + 1; i < toIndex; i++) 64 | elements[i] = -1; 65 | elements[toIndex] = -1L >>> (63 - to.ordinal()); 66 | } 67 | size = to.ordinal() - from.ordinal() + 1; 68 | } 69 | 70 | void addAll() { 71 | for (int i = 0; i < elements.length; i++) 72 | elements[i] = -1; 73 | elements[elements.length - 1] >>>= -universe.length; 74 | size = universe.length; 75 | } 76 | 77 | void complement() { 78 | for (int i = 0; i < elements.length; i++) 79 | elements[i] = ~elements[i]; 80 | elements[elements.length - 1] &= (-1L >>> -universe.length); 81 | size = universe.length - size; 82 | } 83 | 84 | /** 85 | * Returns an iterator over the elements contained in this set. The 86 | * iterator traverses the elements in their natural order (which is 87 | * the order in which the enum constants are declared). The returned 88 | * Iterator is a "weakly consistent" iterator that will never throw {@link 89 | * ConcurrentModificationException}. 90 | * 91 | * @return an iterator over the elements contained in this set 92 | */ 93 | public Iterator iterator() { 94 | return new EnumSetIterator<>(); 95 | } 96 | 97 | private class EnumSetIterator> implements Iterator { 98 | /** 99 | * A bit vector representing the elements in the current "word" 100 | * of the set not yet returned by this iterator. 101 | */ 102 | long unseen; 103 | 104 | /** 105 | * The index corresponding to unseen in the elements array. 106 | */ 107 | int unseenIndex = 0; 108 | 109 | /** 110 | * The bit representing the last element returned by this iterator 111 | * but not removed, or zero if no such element exists. 112 | */ 113 | long lastReturned = 0; 114 | 115 | /** 116 | * The index corresponding to lastReturned in the elements array. 117 | */ 118 | int lastReturnedIndex = 0; 119 | 120 | EnumSetIterator() { 121 | unseen = elements[0]; 122 | } 123 | 124 | @Override 125 | public boolean hasNext() { 126 | while (unseen == 0 && unseenIndex < elements.length - 1) 127 | unseen = elements[++unseenIndex]; 128 | return unseen != 0; 129 | } 130 | 131 | @Override 132 | @SuppressWarnings("unchecked") 133 | public E next() { 134 | if (!hasNext()) 135 | throw new NoSuchElementException(); 136 | lastReturned = unseen & -unseen; 137 | lastReturnedIndex = unseenIndex; 138 | unseen -= lastReturned; 139 | return (E) universe[(lastReturnedIndex << 6) 140 | + Long.numberOfTrailingZeros(lastReturned)]; 141 | } 142 | 143 | @Override 144 | public void remove() { 145 | if (lastReturned == 0) 146 | throw new IllegalStateException(); 147 | final long oldElements = elements[lastReturnedIndex]; 148 | elements[lastReturnedIndex] &= ~lastReturned; 149 | if (oldElements != elements[lastReturnedIndex]) { 150 | size--; 151 | } 152 | lastReturned = 0; 153 | } 154 | } 155 | 156 | /** 157 | * Returns the number of elements in this set. 158 | * 159 | * @return the number of elements in this set 160 | */ 161 | public int size() { 162 | return size; 163 | } 164 | 165 | /** 166 | * Returns {@code true} if this set contains no elements. 167 | * 168 | * @return {@code true} if this set contains no elements 169 | */ 170 | public boolean isEmpty() { 171 | return size == 0; 172 | } 173 | 174 | /** 175 | * Returns {@code true} if this set contains the specified element. 176 | * 177 | * @param e element to be checked for containment in this collection 178 | * @return {@code true} if this set contains the specified element 179 | */ 180 | public boolean contains(Object e) { 181 | if (e == null) 182 | return false; 183 | Class eClass = e.getClass(); 184 | if (eClass != elementType && eClass.getSuperclass() != elementType) 185 | return false; 186 | 187 | int eOrdinal = ((Enum)e).ordinal(); 188 | return (elements[eOrdinal >>> 6] & (1L << eOrdinal)) != 0; 189 | } 190 | 191 | // Modification Operations 192 | 193 | /** 194 | * Adds the specified element to this set if it is not already present. 195 | * 196 | * @param e element to be added to this set 197 | * @return {@code true} if the set changed as a result of the call 198 | * 199 | * @throws NullPointerException if {@code e} is null 200 | */ 201 | public boolean add(E e) { 202 | typeCheck(e); 203 | 204 | int eOrdinal = e.ordinal(); 205 | int eWordNum = eOrdinal >>> 6; 206 | 207 | long oldElements = elements[eWordNum]; 208 | elements[eWordNum] |= (1L << eOrdinal); 209 | boolean result = (elements[eWordNum] != oldElements); 210 | if (result) 211 | size++; 212 | return result; 213 | } 214 | 215 | /** 216 | * Removes the specified element from this set if it is present. 217 | * 218 | * @param e element to be removed from this set, if present 219 | * @return {@code true} if the set contained the specified element 220 | */ 221 | public boolean remove(Object e) { 222 | if (e == null) 223 | return false; 224 | Class eClass = e.getClass(); 225 | if (eClass != elementType && eClass.getSuperclass() != elementType) 226 | return false; 227 | int eOrdinal = ((Enum)e).ordinal(); 228 | int eWordNum = eOrdinal >>> 6; 229 | 230 | long oldElements = elements[eWordNum]; 231 | elements[eWordNum] &= ~(1L << eOrdinal); 232 | boolean result = (elements[eWordNum] != oldElements); 233 | if (result) 234 | size--; 235 | return result; 236 | } 237 | 238 | // Bulk Operations 239 | 240 | /** 241 | * Returns {@code true} if this set contains all of the elements 242 | * in the specified collection. 243 | * 244 | * @param c collection to be checked for containment in this set 245 | * @return {@code true} if this set contains all of the elements 246 | * in the specified collection 247 | * @throws NullPointerException if the specified collection is null 248 | */ 249 | public boolean containsAll(Collection c) { 250 | if (!(c instanceof JumboEnumSet)) 251 | return super.containsAll(c); 252 | 253 | JumboEnumSet es = (JumboEnumSet)c; 254 | if (es.elementType != elementType) 255 | return es.isEmpty(); 256 | 257 | for (int i = 0; i < elements.length; i++) 258 | if ((es.elements[i] & ~elements[i]) != 0) 259 | return false; 260 | return true; 261 | } 262 | 263 | /** 264 | * Adds all of the elements in the specified collection to this set. 265 | * 266 | * @param c collection whose elements are to be added to this set 267 | * @return {@code true} if this set changed as a result of the call 268 | * @throws NullPointerException if the specified collection or any of 269 | * its elements are null 270 | */ 271 | public boolean addAll(Collection c) { 272 | if (!(c instanceof JumboEnumSet)) 273 | return super.addAll(c); 274 | 275 | JumboEnumSet es = (JumboEnumSet)c; 276 | if (es.elementType != elementType) { 277 | if (es.isEmpty()) 278 | return false; 279 | else 280 | throw new ClassCastException( 281 | es.elementType + " != " + elementType); 282 | } 283 | 284 | for (int i = 0; i < elements.length; i++) 285 | elements[i] |= es.elements[i]; 286 | return recalculateSize(); 287 | } 288 | 289 | /** 290 | * Removes from this set all of its elements that are contained in 291 | * the specified collection. 292 | * 293 | * @param c elements to be removed from this set 294 | * @return {@code true} if this set changed as a result of the call 295 | * @throws NullPointerException if the specified collection is null 296 | */ 297 | public boolean removeAll(Collection c) { 298 | if (!(c instanceof JumboEnumSet)) 299 | return super.removeAll(c); 300 | 301 | JumboEnumSet es = (JumboEnumSet)c; 302 | if (es.elementType != elementType) 303 | return false; 304 | 305 | for (int i = 0; i < elements.length; i++) 306 | elements[i] &= ~es.elements[i]; 307 | return recalculateSize(); 308 | } 309 | 310 | /** 311 | * Retains only the elements in this set that are contained in the 312 | * specified collection. 313 | * 314 | * @param c elements to be retained in this set 315 | * @return {@code true} if this set changed as a result of the call 316 | * @throws NullPointerException if the specified collection is null 317 | */ 318 | public boolean retainAll(Collection c) { 319 | if (!(c instanceof JumboEnumSet)) 320 | return super.retainAll(c); 321 | 322 | JumboEnumSet es = (JumboEnumSet)c; 323 | if (es.elementType != elementType) { 324 | boolean changed = (size != 0); 325 | clear(); 326 | return changed; 327 | } 328 | 329 | for (int i = 0; i < elements.length; i++) 330 | elements[i] &= es.elements[i]; 331 | return recalculateSize(); 332 | } 333 | 334 | /** 335 | * Removes all of the elements from this set. 336 | */ 337 | public void clear() { 338 | Arrays.fill(elements, 0); 339 | size = 0; 340 | } 341 | 342 | /** 343 | * Compares the specified object with this set for equality. Returns 344 | * {@code true} if the given object is also a set, the two sets have 345 | * the same size, and every member of the given set is contained in 346 | * this set. 347 | * 348 | * @param o object to be compared for equality with this set 349 | * @return {@code true} if the specified object is equal to this set 350 | */ 351 | public boolean equals(Object o) { 352 | if (!(o instanceof JumboEnumSet)) 353 | return super.equals(o); 354 | 355 | JumboEnumSet es = (JumboEnumSet)o; 356 | if (es.elementType != elementType) 357 | return size == 0 && es.size == 0; 358 | 359 | return Arrays.equals(es.elements, elements); 360 | } 361 | 362 | /** 363 | * Recalculates the size of the set. Returns true if it's changed. 364 | */ 365 | private boolean recalculateSize() { 366 | int oldSize = size; 367 | size = 0; 368 | for (long elt : elements) 369 | size += Long.bitCount(elt); 370 | 371 | return size != oldSize; 372 | } 373 | 374 | public EnumSet clone() { 375 | JumboEnumSet result = (JumboEnumSet) super.clone(); 376 | result.elements = result.elements.clone(); 377 | return result; 378 | } 379 | } 380 | -------------------------------------------------------------------------------- /java/util/SortedMap.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 1998, 2018, 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 | * A {@link Map} that further provides a total ordering on its keys. 30 | * The map is ordered according to the {@linkplain Comparable natural 31 | * ordering} of its keys, or by a {@link Comparator} typically 32 | * provided at sorted map creation time. This order is reflected when 33 | * iterating over the sorted map's collection views (returned by the 34 | * {@code entrySet}, {@code keySet} and {@code values} methods). 35 | * Several additional operations are provided to take advantage of the 36 | * ordering. (This interface is the map analogue of {@link SortedSet}.) 37 | * 38 | *

All keys inserted into a sorted map must implement the {@code Comparable} 39 | * interface (or be accepted by the specified comparator). Furthermore, all 40 | * such keys must be mutually comparable: {@code k1.compareTo(k2)} (or 41 | * {@code comparator.compare(k1, k2)}) must not throw a 42 | * {@code ClassCastException} for any keys {@code k1} and {@code k2} in 43 | * the sorted map. Attempts to violate this restriction will cause the 44 | * offending method or constructor invocation to throw a 45 | * {@code ClassCastException}. 46 | * 47 | *

Note that the ordering maintained by a sorted map (whether or not an 48 | * explicit comparator is provided) must be consistent with equals if 49 | * the sorted map is to correctly implement the {@code Map} interface. (See 50 | * the {@code Comparable} interface or {@code Comparator} interface for a 51 | * precise definition of consistent with equals.) This is so because 52 | * the {@code Map} interface is defined in terms of the {@code equals} 53 | * operation, but a sorted map performs all key comparisons using its 54 | * {@code compareTo} (or {@code compare}) method, so two keys that are 55 | * deemed equal by this method are, from the standpoint of the sorted map, 56 | * equal. The behavior of a tree map is well-defined even if its 57 | * ordering is inconsistent with equals; it just fails to obey the general 58 | * contract of the {@code Map} interface. 59 | * 60 | *

All general-purpose sorted map implementation classes should provide four 61 | * "standard" constructors. It is not possible to enforce this recommendation 62 | * though as required constructors cannot be specified by interfaces. The 63 | * expected "standard" constructors for all sorted map implementations are: 64 | *

    65 | *
  1. A void (no arguments) constructor, which creates an empty sorted map 66 | * sorted according to the natural ordering of its keys.
  2. 67 | *
  3. A constructor with a single argument of type {@code Comparator}, which 68 | * creates an empty sorted map sorted according to the specified comparator.
  4. 69 | *
  5. A constructor with a single argument of type {@code Map}, which creates 70 | * a new map with the same key-value mappings as its argument, sorted 71 | * according to the keys' natural ordering.
  6. 72 | *
  7. A constructor with a single argument of type {@code SortedMap}, which 73 | * creates a new sorted map with the same key-value mappings and the same 74 | * ordering as the input sorted map.
  8. 75 | *
76 | * 77 | *

Note: several methods return submaps with restricted key 78 | * ranges. Such ranges are half-open, that is, they include their low 79 | * endpoint but not their high endpoint (where applicable). If you need a 80 | * closed range (which includes both endpoints), and the key type 81 | * allows for calculation of the successor of a given key, merely request 82 | * the subrange from {@code lowEndpoint} to 83 | * {@code successor(highEndpoint)}. For example, suppose that {@code m} 84 | * is a map whose keys are strings. The following idiom obtains a view 85 | * containing all of the key-value mappings in {@code m} whose keys are 86 | * between {@code low} and {@code high}, inclusive:

 87 |  *   SortedMap<String, V> sub = m.subMap(low, high+"\0");
88 | * 89 | * A similar technique can be used to generate an open range 90 | * (which contains neither endpoint). The following idiom obtains a 91 | * view containing all of the key-value mappings in {@code m} whose keys 92 | * are between {@code low} and {@code high}, exclusive:
 93 |  *   SortedMap<String, V> sub = m.subMap(low+"\0", high);
94 | * 95 | *

This interface is a member of the 96 | * 97 | * Java Collections Framework. 98 | * 99 | * @param the type of keys maintained by this map 100 | * @param the type of mapped values 101 | * 102 | * @author Josh Bloch 103 | * @see Map 104 | * @see TreeMap 105 | * @see SortedSet 106 | * @see Comparator 107 | * @see Comparable 108 | * @see Collection 109 | * @see ClassCastException 110 | * @since 1.2 111 | */ 112 | 113 | public interface SortedMap extends Map { 114 | /** 115 | * Returns the comparator used to order the keys in this map, or 116 | * {@code null} if this map uses the {@linkplain Comparable 117 | * natural ordering} of its keys. 118 | * 119 | * @return the comparator used to order the keys in this map, 120 | * or {@code null} if this map uses the natural ordering 121 | * of its keys 122 | */ 123 | Comparator comparator(); 124 | 125 | /** 126 | * Returns a view of the portion of this map whose keys range from 127 | * {@code fromKey}, inclusive, to {@code toKey}, exclusive. (If 128 | * {@code fromKey} and {@code toKey} are equal, the returned map 129 | * is empty.) The returned map is backed by this map, so changes 130 | * in the returned map are reflected in this map, and vice-versa. 131 | * The returned map supports all optional map operations that this 132 | * map supports. 133 | * 134 | *

The returned map will throw an {@code IllegalArgumentException} 135 | * on an attempt to insert a key outside its range. 136 | * 137 | * @param fromKey low endpoint (inclusive) of the keys in the returned map 138 | * @param toKey high endpoint (exclusive) of the keys in the returned map 139 | * @return a view of the portion of this map whose keys range from 140 | * {@code fromKey}, inclusive, to {@code toKey}, exclusive 141 | * @throws ClassCastException if {@code fromKey} and {@code toKey} 142 | * cannot be compared to one another using this map's comparator 143 | * (or, if the map has no comparator, using natural ordering). 144 | * Implementations may, but are not required to, throw this 145 | * exception if {@code fromKey} or {@code toKey} 146 | * cannot be compared to keys currently in the map. 147 | * @throws NullPointerException if {@code fromKey} or {@code toKey} 148 | * is null and this map does not permit null keys 149 | * @throws IllegalArgumentException if {@code fromKey} is greater than 150 | * {@code toKey}; or if this map itself has a restricted 151 | * range, and {@code fromKey} or {@code toKey} lies 152 | * outside the bounds of the range 153 | */ 154 | SortedMap subMap(K fromKey, K toKey); 155 | 156 | /** 157 | * Returns a view of the portion of this map whose keys are 158 | * strictly less than {@code toKey}. The returned map is backed 159 | * by this map, so changes in the returned map are reflected in 160 | * this map, and vice-versa. The returned map supports all 161 | * optional map operations that this map supports. 162 | * 163 | *

The returned map will throw an {@code IllegalArgumentException} 164 | * on an attempt to insert a key outside its range. 165 | * 166 | * @param toKey high endpoint (exclusive) of the keys in the returned map 167 | * @return a view of the portion of this map whose keys are strictly 168 | * less than {@code toKey} 169 | * @throws ClassCastException if {@code toKey} is not compatible 170 | * with this map's comparator (or, if the map has no comparator, 171 | * if {@code toKey} does not implement {@link Comparable}). 172 | * Implementations may, but are not required to, throw this 173 | * exception if {@code toKey} cannot be compared to keys 174 | * currently in the map. 175 | * @throws NullPointerException if {@code toKey} is null and 176 | * this map does not permit null keys 177 | * @throws IllegalArgumentException if this map itself has a 178 | * restricted range, and {@code toKey} lies outside the 179 | * bounds of the range 180 | */ 181 | SortedMap headMap(K toKey); 182 | 183 | /** 184 | * Returns a view of the portion of this map whose keys are 185 | * greater than or equal to {@code fromKey}. The returned map is 186 | * backed by this map, so changes in the returned map are 187 | * reflected in this map, and vice-versa. The returned map 188 | * supports all optional map operations that this map supports. 189 | * 190 | *

The returned map will throw an {@code IllegalArgumentException} 191 | * on an attempt to insert a key outside its range. 192 | * 193 | * @param fromKey low endpoint (inclusive) of the keys in the returned map 194 | * @return a view of the portion of this map whose keys are greater 195 | * than or equal to {@code fromKey} 196 | * @throws ClassCastException if {@code fromKey} is not compatible 197 | * with this map's comparator (or, if the map has no comparator, 198 | * if {@code fromKey} does not implement {@link Comparable}). 199 | * Implementations may, but are not required to, throw this 200 | * exception if {@code fromKey} cannot be compared to keys 201 | * currently in the map. 202 | * @throws NullPointerException if {@code fromKey} is null and 203 | * this map does not permit null keys 204 | * @throws IllegalArgumentException if this map itself has a 205 | * restricted range, and {@code fromKey} lies outside the 206 | * bounds of the range 207 | */ 208 | SortedMap tailMap(K fromKey); 209 | 210 | /** 211 | * Returns the first (lowest) key currently in this map. 212 | * 213 | * @return the first (lowest) key currently in this map 214 | * @throws NoSuchElementException if this map is empty 215 | */ 216 | K firstKey(); 217 | 218 | /** 219 | * Returns the last (highest) key currently in this map. 220 | * 221 | * @return the last (highest) key currently in this map 222 | * @throws NoSuchElementException if this map is empty 223 | */ 224 | K lastKey(); 225 | 226 | /** 227 | * Returns a {@link Set} view of the keys contained in this map. 228 | * The set's iterator returns the keys in ascending order. 229 | * The set is backed by the map, so changes to the map are 230 | * reflected in the set, and vice-versa. If the map is modified 231 | * while an iteration over the set is in progress (except through 232 | * the iterator's own {@code remove} operation), the results of 233 | * the iteration are undefined. The set supports element removal, 234 | * which removes the corresponding mapping from the map, via the 235 | * {@code Iterator.remove}, {@code Set.remove}, 236 | * {@code removeAll}, {@code retainAll}, and {@code clear} 237 | * operations. It does not support the {@code add} or {@code addAll} 238 | * operations. 239 | * 240 | * @return a set view of the keys contained in this map, sorted in 241 | * ascending order 242 | */ 243 | Set keySet(); 244 | 245 | /** 246 | * Returns a {@link Collection} view of the values contained in this map. 247 | * The collection's iterator returns the values in ascending order 248 | * of the corresponding keys. 249 | * The collection is backed by the map, so changes to the map are 250 | * reflected in the collection, and vice-versa. If the map is 251 | * modified while an iteration over the collection is in progress 252 | * (except through the iterator's own {@code remove} operation), 253 | * the results of the iteration are undefined. The collection 254 | * supports element removal, which removes the corresponding 255 | * mapping from the map, via the {@code Iterator.remove}, 256 | * {@code Collection.remove}, {@code removeAll}, 257 | * {@code retainAll} and {@code clear} operations. It does not 258 | * support the {@code add} or {@code addAll} operations. 259 | * 260 | * @return a collection view of the values contained in this map, 261 | * sorted in ascending key order 262 | */ 263 | Collection values(); 264 | 265 | /** 266 | * Returns a {@link Set} view of the mappings contained in this map. 267 | * The set's iterator returns the entries in ascending key order. 268 | * The set is backed by the map, so changes to the map are 269 | * reflected in the set, and vice-versa. If the map is modified 270 | * while an iteration over the set is in progress (except through 271 | * the iterator's own {@code remove} operation, or through the 272 | * {@code setValue} operation on a map entry returned by the 273 | * iterator) the results of the iteration are undefined. The set 274 | * supports element removal, which removes the corresponding 275 | * mapping from the map, via the {@code Iterator.remove}, 276 | * {@code Set.remove}, {@code removeAll}, {@code retainAll} and 277 | * {@code clear} operations. It does not support the 278 | * {@code add} or {@code addAll} operations. 279 | * 280 | * @return a set view of the mappings contained in this map, 281 | * sorted in ascending key order 282 | */ 283 | Set> entrySet(); 284 | } 285 | -------------------------------------------------------------------------------- /java/util/HashSet.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 1997, 2018, 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 | import java.io.InvalidObjectException; 29 | import jdk.internal.misc.SharedSecrets; 30 | 31 | /** 32 | * This class implements the {@code Set} interface, backed by a hash table 33 | * (actually a {@code HashMap} instance). It makes no guarantees as to the 34 | * iteration order of the set; in particular, it does not guarantee that the 35 | * order will remain constant over time. This class permits the {@code null} 36 | * element. 37 | * 38 | *

This class offers constant time performance for the basic operations 39 | * ({@code add}, {@code remove}, {@code contains} and {@code size}), 40 | * assuming the hash function disperses the elements properly among the 41 | * buckets. Iterating over this set requires time proportional to the sum of 42 | * the {@code HashSet} instance's size (the number of elements) plus the 43 | * "capacity" of the backing {@code HashMap} instance (the number of 44 | * buckets). Thus, it's very important not to set the initial capacity too 45 | * high (or the load factor too low) if iteration performance is important. 46 | * 47 | *

Note that this implementation is not synchronized. 48 | * If multiple threads access a hash set concurrently, and at least one of 49 | * the threads modifies the set, it must be synchronized externally. 50 | * This is typically accomplished by synchronizing on some object that 51 | * naturally encapsulates the set. 52 | * 53 | * If no such object exists, the set should be "wrapped" using the 54 | * {@link Collections#synchronizedSet Collections.synchronizedSet} 55 | * method. This is best done at creation time, to prevent accidental 56 | * unsynchronized access to the set:

 57 |  *   Set s = Collections.synchronizedSet(new HashSet(...));
58 | * 59 | *

The iterators returned by this class's {@code iterator} method are 60 | * fail-fast: if the set is modified at any time after the iterator is 61 | * created, in any way except through the iterator's own {@code remove} 62 | * method, the Iterator throws a {@link ConcurrentModificationException}. 63 | * Thus, in the face of concurrent modification, the iterator fails quickly 64 | * and cleanly, rather than risking arbitrary, non-deterministic behavior at 65 | * an undetermined time in the future. 66 | * 67 | *

Note that the fail-fast behavior of an iterator cannot be guaranteed 68 | * as it is, generally speaking, impossible to make any hard guarantees in the 69 | * presence of unsynchronized concurrent modification. Fail-fast iterators 70 | * throw {@code ConcurrentModificationException} on a best-effort basis. 71 | * Therefore, it would be wrong to write a program that depended on this 72 | * exception for its correctness: the fail-fast behavior of iterators 73 | * should be used only to detect bugs. 74 | * 75 | *

This class is a member of the 76 | * 77 | * Java Collections Framework. 78 | * 79 | * @param the type of elements maintained by this set 80 | * 81 | * @author Josh Bloch 82 | * @author Neal Gafter 83 | * @see Collection 84 | * @see Set 85 | * @see TreeSet 86 | * @see HashMap 87 | * @since 1.2 88 | */ 89 | 90 | public class HashSet 91 | extends AbstractSet 92 | implements Set, Cloneable, java.io.Serializable 93 | { 94 | static final long serialVersionUID = -5024744406713321676L; 95 | 96 | private transient HashMap map; 97 | 98 | // Dummy value to associate with an Object in the backing Map 99 | private static final Object PRESENT = new Object(); 100 | 101 | /** 102 | * Constructs a new, empty set; the backing {@code HashMap} instance has 103 | * default initial capacity (16) and load factor (0.75). 104 | */ 105 | public HashSet() { 106 | map = new HashMap<>(); 107 | } 108 | 109 | /** 110 | * Constructs a new set containing the elements in the specified 111 | * collection. The {@code HashMap} is created with default load factor 112 | * (0.75) and an initial capacity sufficient to contain the elements in 113 | * the specified collection. 114 | * 115 | * @param c the collection whose elements are to be placed into this set 116 | * @throws NullPointerException if the specified collection is null 117 | */ 118 | public HashSet(Collection c) { 119 | map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16)); 120 | addAll(c); 121 | } 122 | 123 | /** 124 | * Constructs a new, empty set; the backing {@code HashMap} instance has 125 | * the specified initial capacity and the specified load factor. 126 | * 127 | * @param initialCapacity the initial capacity of the hash map 128 | * @param loadFactor the load factor of the hash map 129 | * @throws IllegalArgumentException if the initial capacity is less 130 | * than zero, or if the load factor is nonpositive 131 | */ 132 | public HashSet(int initialCapacity, float loadFactor) { 133 | map = new HashMap<>(initialCapacity, loadFactor); 134 | } 135 | 136 | /** 137 | * Constructs a new, empty set; the backing {@code HashMap} instance has 138 | * the specified initial capacity and default load factor (0.75). 139 | * 140 | * @param initialCapacity the initial capacity of the hash table 141 | * @throws IllegalArgumentException if the initial capacity is less 142 | * than zero 143 | */ 144 | public HashSet(int initialCapacity) { 145 | map = new HashMap<>(initialCapacity); 146 | } 147 | 148 | /** 149 | * Constructs a new, empty linked hash set. (This package private 150 | * constructor is only used by LinkedHashSet.) The backing 151 | * HashMap instance is a LinkedHashMap with the specified initial 152 | * capacity and the specified load factor. 153 | * 154 | * @param initialCapacity the initial capacity of the hash map 155 | * @param loadFactor the load factor of the hash map 156 | * @param dummy ignored (distinguishes this 157 | * constructor from other int, float constructor.) 158 | * @throws IllegalArgumentException if the initial capacity is less 159 | * than zero, or if the load factor is nonpositive 160 | */ 161 | HashSet(int initialCapacity, float loadFactor, boolean dummy) { 162 | map = new LinkedHashMap<>(initialCapacity, loadFactor); 163 | } 164 | 165 | /** 166 | * Returns an iterator over the elements in this set. The elements 167 | * are returned in no particular order. 168 | * 169 | * @return an Iterator over the elements in this set 170 | * @see ConcurrentModificationException 171 | */ 172 | public Iterator iterator() { 173 | return map.keySet().iterator(); 174 | } 175 | 176 | /** 177 | * Returns the number of elements in this set (its cardinality). 178 | * 179 | * @return the number of elements in this set (its cardinality) 180 | */ 181 | public int size() { 182 | return map.size(); 183 | } 184 | 185 | /** 186 | * Returns {@code true} if this set contains no elements. 187 | * 188 | * @return {@code true} if this set contains no elements 189 | */ 190 | public boolean isEmpty() { 191 | return map.isEmpty(); 192 | } 193 | 194 | /** 195 | * Returns {@code true} if this set contains the specified element. 196 | * More formally, returns {@code true} if and only if this set 197 | * contains an element {@code e} such that 198 | * {@code Objects.equals(o, e)}. 199 | * 200 | * @param o element whose presence in this set is to be tested 201 | * @return {@code true} if this set contains the specified element 202 | */ 203 | public boolean contains(Object o) { 204 | return map.containsKey(o); 205 | } 206 | 207 | /** 208 | * Adds the specified element to this set if it is not already present. 209 | * More formally, adds the specified element {@code e} to this set if 210 | * this set contains no element {@code e2} such that 211 | * {@code Objects.equals(e, e2)}. 212 | * If this set already contains the element, the call leaves the set 213 | * unchanged and returns {@code false}. 214 | * 215 | * @param e element to be added to this set 216 | * @return {@code true} if this set did not already contain the specified 217 | * element 218 | */ 219 | public boolean add(E e) { 220 | return map.put(e, PRESENT)==null; 221 | } 222 | 223 | /** 224 | * Removes the specified element from this set if it is present. 225 | * More formally, removes an element {@code e} such that 226 | * {@code Objects.equals(o, e)}, 227 | * if this set contains such an element. Returns {@code true} if 228 | * this set contained the element (or equivalently, if this set 229 | * changed as a result of the call). (This set will not contain the 230 | * element once the call returns.) 231 | * 232 | * @param o object to be removed from this set, if present 233 | * @return {@code true} if the set contained the specified element 234 | */ 235 | public boolean remove(Object o) { 236 | return map.remove(o)==PRESENT; 237 | } 238 | 239 | /** 240 | * Removes all of the elements from this set. 241 | * The set will be empty after this call returns. 242 | */ 243 | public void clear() { 244 | map.clear(); 245 | } 246 | 247 | /** 248 | * Returns a shallow copy of this {@code HashSet} instance: the elements 249 | * themselves are not cloned. 250 | * 251 | * @return a shallow copy of this set 252 | */ 253 | @SuppressWarnings("unchecked") 254 | public Object clone() { 255 | try { 256 | HashSet newSet = (HashSet) super.clone(); 257 | newSet.map = (HashMap) map.clone(); 258 | return newSet; 259 | } catch (CloneNotSupportedException e) { 260 | throw new InternalError(e); 261 | } 262 | } 263 | 264 | /** 265 | * Save the state of this {@code HashSet} instance to a stream (that is, 266 | * serialize it). 267 | * 268 | * @serialData The capacity of the backing {@code HashMap} instance 269 | * (int), and its load factor (float) are emitted, followed by 270 | * the size of the set (the number of elements it contains) 271 | * (int), followed by all of its elements (each an Object) in 272 | * no particular order. 273 | */ 274 | private void writeObject(java.io.ObjectOutputStream s) 275 | throws java.io.IOException { 276 | // Write out any hidden serialization magic 277 | s.defaultWriteObject(); 278 | 279 | // Write out HashMap capacity and load factor 280 | s.writeInt(map.capacity()); 281 | s.writeFloat(map.loadFactor()); 282 | 283 | // Write out size 284 | s.writeInt(map.size()); 285 | 286 | // Write out all elements in the proper order. 287 | for (E e : map.keySet()) 288 | s.writeObject(e); 289 | } 290 | 291 | /** 292 | * Reconstitute the {@code HashSet} instance from a stream (that is, 293 | * deserialize it). 294 | */ 295 | private void readObject(java.io.ObjectInputStream s) 296 | throws java.io.IOException, ClassNotFoundException { 297 | // Read in any hidden serialization magic 298 | s.defaultReadObject(); 299 | 300 | // Read capacity and verify non-negative. 301 | int capacity = s.readInt(); 302 | if (capacity < 0) { 303 | throw new InvalidObjectException("Illegal capacity: " + 304 | capacity); 305 | } 306 | 307 | // Read load factor and verify positive and non NaN. 308 | float loadFactor = s.readFloat(); 309 | if (loadFactor <= 0 || Float.isNaN(loadFactor)) { 310 | throw new InvalidObjectException("Illegal load factor: " + 311 | loadFactor); 312 | } 313 | 314 | // Read size and verify non-negative. 315 | int size = s.readInt(); 316 | if (size < 0) { 317 | throw new InvalidObjectException("Illegal size: " + 318 | size); 319 | } 320 | 321 | // Set the capacity according to the size and load factor ensuring that 322 | // the HashMap is at least 25% full but clamping to maximum capacity. 323 | capacity = (int) Math.min(size * Math.min(1 / loadFactor, 4.0f), 324 | HashMap.MAXIMUM_CAPACITY); 325 | 326 | // Constructing the backing map will lazily create an array when the first element is 327 | // added, so check it before construction. Call HashMap.tableSizeFor to compute the 328 | // actual allocation size. Check Map.Entry[].class since it's the nearest public type to 329 | // what is actually created. 330 | SharedSecrets.getJavaObjectInputStreamAccess() 331 | .checkArray(s, Map.Entry[].class, HashMap.tableSizeFor(capacity)); 332 | 333 | // Create backing HashMap 334 | map = (((HashSet)this) instanceof LinkedHashSet ? 335 | new LinkedHashMap<>(capacity, loadFactor) : 336 | new HashMap<>(capacity, loadFactor)); 337 | 338 | // Read in all elements in the proper order. 339 | for (int i=0; ilate-binding 348 | * and fail-fast {@link Spliterator} over the elements in this 349 | * set. 350 | * 351 | *

The {@code Spliterator} reports {@link Spliterator#SIZED} and 352 | * {@link Spliterator#DISTINCT}. Overriding implementations should document 353 | * the reporting of additional characteristic values. 354 | * 355 | * @return a {@code Spliterator} over the elements in this set 356 | * @since 1.8 357 | */ 358 | public Spliterator spliterator() { 359 | return new HashMap.KeySpliterator<>(map, 0, -1, 0, 0); 360 | } 361 | } 362 | -------------------------------------------------------------------------------- /java/util/NavigableSet.java: -------------------------------------------------------------------------------- 1 | /* 2 | * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 3 | * 4 | * This code is free software; you can redistribute it and/or modify it 5 | * under the terms of the GNU General Public License version 2 only, as 6 | * published by the Free Software Foundation. Oracle designates this 7 | * particular file as subject to the "Classpath" exception as provided 8 | * by Oracle in the LICENSE file that accompanied this code. 9 | * 10 | * This code is distributed in the hope that it will be useful, but WITHOUT 11 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 12 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 13 | * version 2 for more details (a copy is included in the LICENSE file that 14 | * accompanied this code). 15 | * 16 | * You should have received a copy of the GNU General Public License version 17 | * 2 along with this work; if not, write to the Free Software Foundation, 18 | * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 19 | * 20 | * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 21 | * or visit www.oracle.com if you need additional information or have any 22 | * questions. 23 | */ 24 | 25 | /* 26 | * This file is available under and governed by the GNU General Public 27 | * License version 2 only, as published by the Free Software Foundation. 28 | * However, the following notice accompanied the original version of this 29 | * file: 30 | * 31 | * Written by Doug Lea and Josh Bloch with assistance from members of JCP 32 | * JSR-166 Expert Group and released to the public domain, as explained at 33 | * http://creativecommons.org/publicdomain/zero/1.0/ 34 | */ 35 | 36 | package java.util; 37 | 38 | /** 39 | * A {@link SortedSet} extended with navigation methods reporting 40 | * closest matches for given search targets. Methods {@link #lower}, 41 | * {@link #floor}, {@link #ceiling}, and {@link #higher} return elements 42 | * respectively less than, less than or equal, greater than or equal, 43 | * and greater than a given element, returning {@code null} if there 44 | * is no such element. 45 | * 46 | *

A {@code NavigableSet} may be accessed and traversed in either 47 | * ascending or descending order. The {@link #descendingSet} method 48 | * returns a view of the set with the senses of all relational and 49 | * directional methods inverted. The performance of ascending 50 | * operations and views is likely to be faster than that of descending 51 | * ones. This interface additionally defines methods {@link 52 | * #pollFirst} and {@link #pollLast} that return and remove the lowest 53 | * and highest element, if one exists, else returning {@code null}. 54 | * Methods 55 | * {@link #subSet(Object, boolean, Object, boolean) subSet(E, boolean, E, boolean)}, 56 | * {@link #headSet(Object, boolean) headSet(E, boolean)}, and 57 | * {@link #tailSet(Object, boolean) tailSet(E, boolean)} 58 | * differ from the like-named {@code SortedSet} methods in accepting 59 | * additional arguments describing whether lower and upper bounds are 60 | * inclusive versus exclusive. Subsets of any {@code NavigableSet} 61 | * must implement the {@code NavigableSet} interface. 62 | * 63 | *

The return values of navigation methods may be ambiguous in 64 | * implementations that permit {@code null} elements. However, even 65 | * in this case the result can be disambiguated by checking 66 | * {@code contains(null)}. To avoid such issues, implementations of 67 | * this interface are encouraged to not permit insertion of 68 | * {@code null} elements. (Note that sorted sets of {@link 69 | * Comparable} elements intrinsically do not permit {@code null}.) 70 | * 71 | *

Methods 72 | * {@link #subSet(Object, Object) subSet(E, E)}, 73 | * {@link #headSet(Object) headSet(E)}, and 74 | * {@link #tailSet(Object) tailSet(E)} 75 | * are specified to return {@code SortedSet} to allow existing 76 | * implementations of {@code SortedSet} to be compatibly retrofitted to 77 | * implement {@code NavigableSet}, but extensions and implementations 78 | * of this interface are encouraged to override these methods to return 79 | * {@code NavigableSet}. 80 | * 81 | *

This interface is a member of the 82 | * 83 | * Java Collections Framework. 84 | * 85 | * @author Doug Lea 86 | * @author Josh Bloch 87 | * @param the type of elements maintained by this set 88 | * @since 1.6 89 | */ 90 | public interface NavigableSet extends SortedSet { 91 | /** 92 | * Returns the greatest element in this set strictly less than the 93 | * given element, or {@code null} if there is no such element. 94 | * 95 | * @param e the value to match 96 | * @return the greatest element less than {@code e}, 97 | * or {@code null} if there is no such element 98 | * @throws ClassCastException if the specified element cannot be 99 | * compared with the elements currently in the set 100 | * @throws NullPointerException if the specified element is null 101 | * and this set does not permit null elements 102 | */ 103 | E lower(E e); 104 | 105 | /** 106 | * Returns the greatest element in this set less than or equal to 107 | * the given element, or {@code null} if there is no such element. 108 | * 109 | * @param e the value to match 110 | * @return the greatest element less than or equal to {@code e}, 111 | * or {@code null} if there is no such element 112 | * @throws ClassCastException if the specified element cannot be 113 | * compared with the elements currently in the set 114 | * @throws NullPointerException if the specified element is null 115 | * and this set does not permit null elements 116 | */ 117 | E floor(E e); 118 | 119 | /** 120 | * Returns the least element in this set greater than or equal to 121 | * the given element, or {@code null} if there is no such element. 122 | * 123 | * @param e the value to match 124 | * @return the least element greater than or equal to {@code e}, 125 | * or {@code null} if there is no such element 126 | * @throws ClassCastException if the specified element cannot be 127 | * compared with the elements currently in the set 128 | * @throws NullPointerException if the specified element is null 129 | * and this set does not permit null elements 130 | */ 131 | E ceiling(E e); 132 | 133 | /** 134 | * Returns the least element in this set strictly greater than the 135 | * given element, or {@code null} if there is no such element. 136 | * 137 | * @param e the value to match 138 | * @return the least element greater than {@code e}, 139 | * or {@code null} if there is no such element 140 | * @throws ClassCastException if the specified element cannot be 141 | * compared with the elements currently in the set 142 | * @throws NullPointerException if the specified element is null 143 | * and this set does not permit null elements 144 | */ 145 | E higher(E e); 146 | 147 | /** 148 | * Retrieves and removes the first (lowest) element, 149 | * or returns {@code null} if this set is empty. 150 | * 151 | * @return the first element, or {@code null} if this set is empty 152 | */ 153 | E pollFirst(); 154 | 155 | /** 156 | * Retrieves and removes the last (highest) element, 157 | * or returns {@code null} if this set is empty. 158 | * 159 | * @return the last element, or {@code null} if this set is empty 160 | */ 161 | E pollLast(); 162 | 163 | /** 164 | * Returns an iterator over the elements in this set, in ascending order. 165 | * 166 | * @return an iterator over the elements in this set, in ascending order 167 | */ 168 | Iterator iterator(); 169 | 170 | /** 171 | * Returns a reverse order view of the elements contained in this set. 172 | * The descending set is backed by this set, so changes to the set are 173 | * reflected in the descending set, and vice-versa. If either set is 174 | * modified while an iteration over either set is in progress (except 175 | * through the iterator's own {@code remove} operation), the results of 176 | * the iteration are undefined. 177 | * 178 | *

The returned set has an ordering equivalent to 179 | * {@link Collections#reverseOrder(Comparator) Collections.reverseOrder}{@code (comparator())}. 180 | * The expression {@code s.descendingSet().descendingSet()} returns a 181 | * view of {@code s} essentially equivalent to {@code s}. 182 | * 183 | * @return a reverse order view of this set 184 | */ 185 | NavigableSet descendingSet(); 186 | 187 | /** 188 | * Returns an iterator over the elements in this set, in descending order. 189 | * Equivalent in effect to {@code descendingSet().iterator()}. 190 | * 191 | * @return an iterator over the elements in this set, in descending order 192 | */ 193 | Iterator descendingIterator(); 194 | 195 | /** 196 | * Returns a view of the portion of this set whose elements range from 197 | * {@code fromElement} to {@code toElement}. If {@code fromElement} and 198 | * {@code toElement} are equal, the returned set is empty unless {@code 199 | * fromInclusive} and {@code toInclusive} are both true. The returned set 200 | * is backed by this set, so changes in the returned set are reflected in 201 | * this set, and vice-versa. The returned set supports all optional set 202 | * operations that this set supports. 203 | * 204 | *

The returned set will throw an {@code IllegalArgumentException} 205 | * on an attempt to insert an element outside its range. 206 | * 207 | * @param fromElement low endpoint of the returned set 208 | * @param fromInclusive {@code true} if the low endpoint 209 | * is to be included in the returned view 210 | * @param toElement high endpoint of the returned set 211 | * @param toInclusive {@code true} if the high endpoint 212 | * is to be included in the returned view 213 | * @return a view of the portion of this set whose elements range from 214 | * {@code fromElement}, inclusive, to {@code toElement}, exclusive 215 | * @throws ClassCastException if {@code fromElement} and 216 | * {@code toElement} cannot be compared to one another using this 217 | * set's comparator (or, if the set has no comparator, using 218 | * natural ordering). Implementations may, but are not required 219 | * to, throw this exception if {@code fromElement} or 220 | * {@code toElement} cannot be compared to elements currently in 221 | * the set. 222 | * @throws NullPointerException if {@code fromElement} or 223 | * {@code toElement} is null and this set does 224 | * not permit null elements 225 | * @throws IllegalArgumentException if {@code fromElement} is 226 | * greater than {@code toElement}; or if this set itself 227 | * has a restricted range, and {@code fromElement} or 228 | * {@code toElement} lies outside the bounds of the range. 229 | */ 230 | NavigableSet subSet(E fromElement, boolean fromInclusive, 231 | E toElement, boolean toInclusive); 232 | 233 | /** 234 | * Returns a view of the portion of this set whose elements are less than 235 | * (or equal to, if {@code inclusive} is true) {@code toElement}. The 236 | * returned set is backed by this set, so changes in the returned set are 237 | * reflected in this set, and vice-versa. The returned set supports all 238 | * optional set operations that this set supports. 239 | * 240 | *

The returned set will throw an {@code IllegalArgumentException} 241 | * on an attempt to insert an element outside its range. 242 | * 243 | * @param toElement high endpoint of the returned set 244 | * @param inclusive {@code true} if the high endpoint 245 | * is to be included in the returned view 246 | * @return a view of the portion of this set whose elements are less than 247 | * (or equal to, if {@code inclusive} is true) {@code toElement} 248 | * @throws ClassCastException if {@code toElement} is not compatible 249 | * with this set's comparator (or, if the set has no comparator, 250 | * if {@code toElement} does not implement {@link Comparable}). 251 | * Implementations may, but are not required to, throw this 252 | * exception if {@code toElement} cannot be compared to elements 253 | * currently in the set. 254 | * @throws NullPointerException if {@code toElement} is null and 255 | * this set does not permit null elements 256 | * @throws IllegalArgumentException if this set itself has a 257 | * restricted range, and {@code toElement} lies outside the 258 | * bounds of the range 259 | */ 260 | NavigableSet headSet(E toElement, boolean inclusive); 261 | 262 | /** 263 | * Returns a view of the portion of this set whose elements are greater 264 | * than (or equal to, if {@code inclusive} is true) {@code fromElement}. 265 | * The returned set is backed by this set, so changes in the returned set 266 | * are reflected in this set, and vice-versa. The returned set supports 267 | * all optional set operations that this set supports. 268 | * 269 | *

The returned set will throw an {@code IllegalArgumentException} 270 | * on an attempt to insert an element outside its range. 271 | * 272 | * @param fromElement low endpoint of the returned set 273 | * @param inclusive {@code true} if the low endpoint 274 | * is to be included in the returned view 275 | * @return a view of the portion of this set whose elements are greater 276 | * than or equal to {@code fromElement} 277 | * @throws ClassCastException if {@code fromElement} is not compatible 278 | * with this set's comparator (or, if the set has no comparator, 279 | * if {@code fromElement} does not implement {@link Comparable}). 280 | * Implementations may, but are not required to, throw this 281 | * exception if {@code fromElement} cannot be compared to elements 282 | * currently in the set. 283 | * @throws NullPointerException if {@code fromElement} is null 284 | * and this set does not permit null elements 285 | * @throws IllegalArgumentException if this set itself has a 286 | * restricted range, and {@code fromElement} lies outside the 287 | * bounds of the range 288 | */ 289 | NavigableSet tailSet(E fromElement, boolean inclusive); 290 | 291 | /** 292 | * {@inheritDoc} 293 | * 294 | *

Equivalent to {@code subSet(fromElement, true, toElement, false)}. 295 | * 296 | * @throws ClassCastException {@inheritDoc} 297 | * @throws NullPointerException {@inheritDoc} 298 | * @throws IllegalArgumentException {@inheritDoc} 299 | */ 300 | SortedSet subSet(E fromElement, E toElement); 301 | 302 | /** 303 | * {@inheritDoc} 304 | * 305 | *

Equivalent to {@code headSet(toElement, false)}. 306 | * 307 | * @throws ClassCastException {@inheritDoc} 308 | * @throws NullPointerException {@inheritDoc} 309 | * @throws IllegalArgumentException {@inheritDoc} 310 | */ 311 | SortedSet headSet(E toElement); 312 | 313 | /** 314 | * {@inheritDoc} 315 | * 316 | *

Equivalent to {@code tailSet(fromElement, true)}. 317 | * 318 | * @throws ClassCastException {@inheritDoc} 319 | * @throws NullPointerException {@inheritDoc} 320 | * @throws IllegalArgumentException {@inheritDoc} 321 | */ 322 | SortedSet tailSet(E fromElement); 323 | } 324 | -------------------------------------------------------------------------------- /java/util/concurrent/CopyOnWriteArraySet.java: -------------------------------------------------------------------------------- 1 | /* 2 | * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 3 | * 4 | * This code is free software; you can redistribute it and/or modify it 5 | * under the terms of the GNU General Public License version 2 only, as 6 | * published by the Free Software Foundation. Oracle designates this 7 | * particular file as subject to the "Classpath" exception as provided 8 | * by Oracle in the LICENSE file that accompanied this code. 9 | * 10 | * This code is distributed in the hope that it will be useful, but WITHOUT 11 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 12 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 13 | * version 2 for more details (a copy is included in the LICENSE file that 14 | * accompanied this code). 15 | * 16 | * You should have received a copy of the GNU General Public License version 17 | * 2 along with this work; if not, write to the Free Software Foundation, 18 | * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 19 | * 20 | * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 21 | * or visit www.oracle.com if you need additional information or have any 22 | * questions. 23 | */ 24 | 25 | /* 26 | * This file is available under and governed by the GNU General Public 27 | * License version 2 only, as published by the Free Software Foundation. 28 | * However, the following notice accompanied the original version of this 29 | * file: 30 | * 31 | * Written by Doug Lea with assistance from members of JCP JSR-166 32 | * Expert Group and released to the public domain, as explained at 33 | * http://creativecommons.org/publicdomain/zero/1.0/ 34 | */ 35 | 36 | package java.util.concurrent; 37 | 38 | import java.util.AbstractSet; 39 | import java.util.Collection; 40 | import java.util.Iterator; 41 | import java.util.Objects; 42 | import java.util.Set; 43 | import java.util.Spliterator; 44 | import java.util.Spliterators; 45 | import java.util.function.Consumer; 46 | import java.util.function.Predicate; 47 | 48 | /** 49 | * A {@link Set} that uses an internal {@link CopyOnWriteArrayList} 50 | * for all of its operations. Thus, it shares the same basic properties: 51 | *

    52 | *
  • It is best suited for applications in which set sizes generally 53 | * stay small, read-only operations 54 | * vastly outnumber mutative operations, and you need 55 | * to prevent interference among threads during traversal. 56 | *
  • It is thread-safe. 57 | *
  • Mutative operations ({@code add}, {@code set}, {@code remove}, etc.) 58 | * are expensive since they usually entail copying the entire underlying 59 | * array. 60 | *
  • Iterators do not support the mutative {@code remove} operation. 61 | *
  • Traversal via iterators is fast and cannot encounter 62 | * interference from other threads. Iterators rely on 63 | * unchanging snapshots of the array at the time the iterators were 64 | * constructed. 65 | *
66 | * 67 | *

Sample Usage. The following code sketch uses a 68 | * copy-on-write set to maintain a set of Handler objects that 69 | * perform some action upon state updates. 70 | * 71 | *

 {@code
 72 |  * class Handler { void handle(); ... }
 73 |  *
 74 |  * class X {
 75 |  *   private final CopyOnWriteArraySet handlers
 76 |  *     = new CopyOnWriteArraySet<>();
 77 |  *   public void addHandler(Handler h) { handlers.add(h); }
 78 |  *
 79 |  *   private long internalState;
 80 |  *   private synchronized void changeState() { internalState = ...; }
 81 |  *
 82 |  *   public void update() {
 83 |  *     changeState();
 84 |  *     for (Handler handler : handlers)
 85 |  *       handler.handle();
 86 |  *   }
 87 |  * }}
88 | * 89 | *

This class is a member of the 90 | * 91 | * Java Collections Framework. 92 | * 93 | * @see CopyOnWriteArrayList 94 | * @since 1.5 95 | * @author Doug Lea 96 | * @param the type of elements held in this set 97 | */ 98 | public class CopyOnWriteArraySet extends AbstractSet 99 | implements java.io.Serializable { 100 | private static final long serialVersionUID = 5457747651344034263L; 101 | 102 | private final CopyOnWriteArrayList al; 103 | 104 | /** 105 | * Creates an empty set. 106 | */ 107 | public CopyOnWriteArraySet() { 108 | al = new CopyOnWriteArrayList(); 109 | } 110 | 111 | /** 112 | * Creates a set containing all of the elements of the specified 113 | * collection. 114 | * 115 | * @param c the collection of elements to initially contain 116 | * @throws NullPointerException if the specified collection is null 117 | */ 118 | public CopyOnWriteArraySet(Collection c) { 119 | if (c.getClass() == CopyOnWriteArraySet.class) { 120 | @SuppressWarnings("unchecked") CopyOnWriteArraySet cc = 121 | (CopyOnWriteArraySet)c; 122 | al = new CopyOnWriteArrayList(cc.al); 123 | } 124 | else { 125 | al = new CopyOnWriteArrayList(); 126 | al.addAllAbsent(c); 127 | } 128 | } 129 | 130 | /** 131 | * Returns the number of elements in this set. 132 | * 133 | * @return the number of elements in this set 134 | */ 135 | public int size() { 136 | return al.size(); 137 | } 138 | 139 | /** 140 | * Returns {@code true} if this set contains no elements. 141 | * 142 | * @return {@code true} if this set contains no elements 143 | */ 144 | public boolean isEmpty() { 145 | return al.isEmpty(); 146 | } 147 | 148 | /** 149 | * Returns {@code true} if this set contains the specified element. 150 | * More formally, returns {@code true} if and only if this set 151 | * contains an element {@code e} such that {@code Objects.equals(o, e)}. 152 | * 153 | * @param o element whose presence in this set is to be tested 154 | * @return {@code true} if this set contains the specified element 155 | */ 156 | public boolean contains(Object o) { 157 | return al.contains(o); 158 | } 159 | 160 | /** 161 | * Returns an array containing all of the elements in this set. 162 | * If this set makes any guarantees as to what order its elements 163 | * are returned by its iterator, this method must return the 164 | * elements in the same order. 165 | * 166 | *

The returned array will be "safe" in that no references to it 167 | * are maintained by this set. (In other words, this method must 168 | * allocate a new array even if this set is backed by an array). 169 | * The caller is thus free to modify the returned array. 170 | * 171 | *

This method acts as bridge between array-based and collection-based 172 | * APIs. 173 | * 174 | * @return an array containing all the elements in this set 175 | */ 176 | public Object[] toArray() { 177 | return al.toArray(); 178 | } 179 | 180 | /** 181 | * Returns an array containing all of the elements in this set; the 182 | * runtime type of the returned array is that of the specified array. 183 | * If the set fits in the specified array, it is returned therein. 184 | * Otherwise, a new array is allocated with the runtime type of the 185 | * specified array and the size of this set. 186 | * 187 | *

If this set fits in the specified array with room to spare 188 | * (i.e., the array has more elements than this set), the element in 189 | * the array immediately following the end of the set is set to 190 | * {@code null}. (This is useful in determining the length of this 191 | * set only if the caller knows that this set does not contain 192 | * any null elements.) 193 | * 194 | *

If this set makes any guarantees as to what order its elements 195 | * are returned by its iterator, this method must return the elements 196 | * in the same order. 197 | * 198 | *

Like the {@link #toArray()} method, this method acts as bridge between 199 | * array-based and collection-based APIs. Further, this method allows 200 | * precise control over the runtime type of the output array, and may, 201 | * under certain circumstances, be used to save allocation costs. 202 | * 203 | *

Suppose {@code x} is a set known to contain only strings. 204 | * The following code can be used to dump the set into a newly allocated 205 | * array of {@code String}: 206 | * 207 | *

 {@code String[] y = x.toArray(new String[0]);}
208 | * 209 | * Note that {@code toArray(new Object[0])} is identical in function to 210 | * {@code toArray()}. 211 | * 212 | * @param a the array into which the elements of this set are to be 213 | * stored, if it is big enough; otherwise, a new array of the same 214 | * runtime type is allocated for this purpose. 215 | * @return an array containing all the elements in this set 216 | * @throws ArrayStoreException if the runtime type of the specified array 217 | * is not a supertype of the runtime type of every element in this 218 | * set 219 | * @throws NullPointerException if the specified array is null 220 | */ 221 | public T[] toArray(T[] a) { 222 | return al.toArray(a); 223 | } 224 | 225 | /** 226 | * Removes all of the elements from this set. 227 | * The set will be empty after this call returns. 228 | */ 229 | public void clear() { 230 | al.clear(); 231 | } 232 | 233 | /** 234 | * Removes the specified element from this set if it is present. 235 | * More formally, removes an element {@code e} such that 236 | * {@code Objects.equals(o, e)}, if this set contains such an element. 237 | * Returns {@code true} if this set contained the element (or 238 | * equivalently, if this set changed as a result of the call). 239 | * (This set will not contain the element once the call returns.) 240 | * 241 | * @param o object to be removed from this set, if present 242 | * @return {@code true} if this set contained the specified element 243 | */ 244 | public boolean remove(Object o) { 245 | return al.remove(o); 246 | } 247 | 248 | /** 249 | * Adds the specified element to this set if it is not already present. 250 | * More formally, adds the specified element {@code e} to this set if 251 | * the set contains no element {@code e2} such that 252 | * {@code Objects.equals(e, e2)}. 253 | * If this set already contains the element, the call leaves the set 254 | * unchanged and returns {@code false}. 255 | * 256 | * @param e element to be added to this set 257 | * @return {@code true} if this set did not already contain the specified 258 | * element 259 | */ 260 | public boolean add(E e) { 261 | return al.addIfAbsent(e); 262 | } 263 | 264 | /** 265 | * Returns {@code true} if this set contains all of the elements of the 266 | * specified collection. If the specified collection is also a set, this 267 | * method returns {@code true} if it is a subset of this set. 268 | * 269 | * @param c collection to be checked for containment in this set 270 | * @return {@code true} if this set contains all of the elements of the 271 | * specified collection 272 | * @throws NullPointerException if the specified collection is null 273 | * @see #contains(Object) 274 | */ 275 | public boolean containsAll(Collection c) { 276 | return (c instanceof Set) 277 | ? compareSets(al.getArray(), (Set) c) >= 0 278 | : al.containsAll(c); 279 | } 280 | 281 | /** 282 | * Tells whether the objects in snapshot (regarded as a set) are a 283 | * superset of the given set. 284 | * 285 | * @return -1 if snapshot is not a superset, 0 if the two sets 286 | * contain precisely the same elements, and 1 if snapshot is a 287 | * proper superset of the given set 288 | */ 289 | private static int compareSets(Object[] snapshot, Set set) { 290 | // Uses O(n^2) algorithm, that is only appropriate for small 291 | // sets, which CopyOnWriteArraySets should be. 292 | // 293 | // Optimize up to O(n) if the two sets share a long common prefix, 294 | // as might happen if one set was created as a copy of the other set. 295 | 296 | final int len = snapshot.length; 297 | // Mark matched elements to avoid re-checking 298 | final boolean[] matched = new boolean[len]; 299 | 300 | // j is the largest int with matched[i] true for { i | 0 <= i < j } 301 | int j = 0; 302 | outer: for (Object x : set) { 303 | for (int i = j; i < len; i++) { 304 | if (!matched[i] && Objects.equals(x, snapshot[i])) { 305 | matched[i] = true; 306 | if (i == j) 307 | do { j++; } while (j < len && matched[j]); 308 | continue outer; 309 | } 310 | } 311 | return -1; 312 | } 313 | return (j == len) ? 0 : 1; 314 | } 315 | 316 | /** 317 | * Adds all of the elements in the specified collection to this set if 318 | * they're not already present. If the specified collection is also a 319 | * set, the {@code addAll} operation effectively modifies this set so 320 | * that its value is the union of the two sets. The behavior of 321 | * this operation is undefined if the specified collection is modified 322 | * while the operation is in progress. 323 | * 324 | * @param c collection containing elements to be added to this set 325 | * @return {@code true} if this set changed as a result of the call 326 | * @throws NullPointerException if the specified collection is null 327 | * @see #add(Object) 328 | */ 329 | public boolean addAll(Collection c) { 330 | return al.addAllAbsent(c) > 0; 331 | } 332 | 333 | /** 334 | * Removes from this set all of its elements that are contained in the 335 | * specified collection. If the specified collection is also a set, 336 | * this operation effectively modifies this set so that its value is the 337 | * asymmetric set difference of the two sets. 338 | * 339 | * @param c collection containing elements to be removed from this set 340 | * @return {@code true} if this set changed as a result of the call 341 | * @throws ClassCastException if the class of an element of this set 342 | * is incompatible with the specified collection 343 | * (optional) 344 | * @throws NullPointerException if this set contains a null element and the 345 | * specified collection does not permit null elements 346 | * (optional), 347 | * or if the specified collection is null 348 | * @see #remove(Object) 349 | */ 350 | public boolean removeAll(Collection c) { 351 | return al.removeAll(c); 352 | } 353 | 354 | /** 355 | * Retains only the elements in this set that are contained in the 356 | * specified collection. In other words, removes from this set all of 357 | * its elements that are not contained in the specified collection. If 358 | * the specified collection is also a set, this operation effectively 359 | * modifies this set so that its value is the intersection of the 360 | * two sets. 361 | * 362 | * @param c collection containing elements to be retained in this set 363 | * @return {@code true} if this set changed as a result of the call 364 | * @throws ClassCastException if the class of an element of this set 365 | * is incompatible with the specified collection 366 | * (optional) 367 | * @throws NullPointerException if this set contains a null element and the 368 | * specified collection does not permit null elements 369 | * (optional), 370 | * or if the specified collection is null 371 | * @see #remove(Object) 372 | */ 373 | public boolean retainAll(Collection c) { 374 | return al.retainAll(c); 375 | } 376 | 377 | /** 378 | * Returns an iterator over the elements contained in this set 379 | * in the order in which these elements were added. 380 | * 381 | *

The returned iterator provides a snapshot of the state of the set 382 | * when the iterator was constructed. No synchronization is needed while 383 | * traversing the iterator. The iterator does NOT support the 384 | * {@code remove} method. 385 | * 386 | * @return an iterator over the elements in this set 387 | */ 388 | public Iterator iterator() { 389 | return al.iterator(); 390 | } 391 | 392 | /** 393 | * Compares the specified object with this set for equality. 394 | * Returns {@code true} if the specified object is the same object 395 | * as this object, or if it is also a {@link Set} and the elements 396 | * returned by an {@linkplain Set#iterator() iterator} over the 397 | * specified set are the same as the elements returned by an 398 | * iterator over this set. More formally, the two iterators are 399 | * considered to return the same elements if they return the same 400 | * number of elements and for every element {@code e1} returned by 401 | * the iterator over the specified set, there is an element 402 | * {@code e2} returned by the iterator over this set such that 403 | * {@code Objects.equals(e1, e2)}. 404 | * 405 | * @param o object to be compared for equality with this set 406 | * @return {@code true} if the specified object is equal to this set 407 | */ 408 | public boolean equals(Object o) { 409 | return (o == this) 410 | || ((o instanceof Set) 411 | && compareSets(al.getArray(), (Set) o) == 0); 412 | } 413 | 414 | /** 415 | * @throws NullPointerException {@inheritDoc} 416 | */ 417 | public boolean removeIf(Predicate filter) { 418 | return al.removeIf(filter); 419 | } 420 | 421 | /** 422 | * @throws NullPointerException {@inheritDoc} 423 | */ 424 | public void forEach(Consumer action) { 425 | al.forEach(action); 426 | } 427 | 428 | /** 429 | * Returns a {@link Spliterator} over the elements in this set in the order 430 | * in which these elements were added. 431 | * 432 | *

The {@code Spliterator} reports {@link Spliterator#IMMUTABLE}, 433 | * {@link Spliterator#DISTINCT}, {@link Spliterator#SIZED}, and 434 | * {@link Spliterator#SUBSIZED}. 435 | * 436 | *

The spliterator provides a snapshot of the state of the set 437 | * when the spliterator was constructed. No synchronization is needed while 438 | * operating on the spliterator. 439 | * 440 | * @return a {@code Spliterator} over the elements in this set 441 | * @since 1.8 442 | */ 443 | public Spliterator spliterator() { 444 | return Spliterators.spliterator 445 | (al.getArray(), Spliterator.IMMUTABLE | Spliterator.DISTINCT); 446 | } 447 | } 448 | --------------------------------------------------------------------------------