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. <p>
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).<p>
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}.<p>
43  *
44  * This class is a member of the
45  * <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
46  * Java Collections Framework</a>.
47  *
48  * @param <E> 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<E> extends AbstractCollection<E> implements Set<E> {
59     /**
60      * Sole constructor.  (For invocation by subclass constructors, typically
61      * implicit.)
62      */
AbstractSet()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.<p>
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      */
equals(Object o)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      * <p>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      */
hashCode()118     public int hashCode() {
119         int h = 0;
120         Iterator<E> 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 <i>asymmetric set difference</i> of
134      * the two sets.
135      *
136      * <p>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      * <p>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      * (<a href="Collection.html#optional-restrictions">optional</a>)
159      * @throws NullPointerException if this set contains a null element and the
160      *         specified collection does not permit null elements
161      * (<a href="Collection.html#optional-restrictions">optional</a>),
162      *         or if the specified collection is null
163      * @see #remove(Object)
164      * @see #contains(Object)
165      */
removeAll(Collection<?> c)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