1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
/*
 * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */
package Torello.Java.ReadOnly;

import Torello.Java.Additional.RemoveUnsupportedIterator;

import java.util.*;

import java.util.function.Predicate;

/**
 * A Copy of Java's {@code HashSet} class; used for building a {@link ReadOnlyHashSet}.  Maintains
 * <I>an internal and inaccessible {@code HashSet<E>} instance</I>. 
 * 
 * <EMBED CLASS=globalDefs DATA-JDK=HashSet>
 * <EMBED CLASS='external-html' DATA-A_AN=a DATA-FILE-ID=BUILDERS>
 * 
 * @param <E> the type of elements maintained by this set
 * @see ReadOnlyHashSet
 */
@Torello.JavaDoc.JDHeaderBackgroundImg(EmbedTagFileID="JDHBI_BUILDER")
public final class ROHashSetBuilder<E>
    extends HashSet<E>
    implements Cloneable, java.io.Serializable
{
    // ********************************************************************************************
    // ********************************************************************************************
    // Fields & Builder
    // ********************************************************************************************
    // ********************************************************************************************


    /** <EMBED CLASS='external-html' DATA-FILE-ID=SVUID> */
    protected static final long serialVersionUID = 1;

    // Exception messages need this
    private static final String ROHS = "HashSet";

    private boolean built = false;

    // Mimics the C++ Concept of "Friend Class".  This badge is utilized by the "build()" method
    // directly below this inner-class declaration.  It is the only place where this declaration is
    // actually used anywhere.  This prohibits access to the constructor that is used to anybody
    // else

    static class AccessBadge { private AccessBadge() { } }
    private static final AccessBadge friendClassBadge = new AccessBadge();

    /**
     * Simply transfers {@code 'this'} instance' internal {@code HashSet} to the 
     * {@code ReadOnlyHashSet} Wrapper-Class.
     * 
     * @return a newly constructed {@code ReadOnlyHashSet} "Wrapper-Class", shielding the
     * internal {@code 'hashSet'} private-field from any modification.
     */
    public ReadOnlyHashSet<E> build()
    {
        this.built = true;

        return (size() == 0)
            ? ReadOnlyHashSet.emptyROHS()
            : new ReadOnlyHashSet<E>(this, friendClassBadge);
    }


    // ********************************************************************************************
    // ********************************************************************************************
    // Modified Constructors
    // ********************************************************************************************
    // ********************************************************************************************


    /**
     * Constructs a new, empty {@code ROHashSetBuilder}, the underlying {@code HashMap} instance
     * has default initial capacity (16) and load factor (0.75).
     */
    public ROHashSetBuilder()
    { super(); }

    /**
     * Constructs a new {@code ROHashSetBuilder} containing the elements in the specified
     * collection.  The underlying {@code HashMap} is created with default load factor (0.75) and
     * an initial capacity sufficient to contain the elements in the specified collection.
     *
     * @param c the collection whose elements are to be placed into this set
     * @throws NullPointerException if the specified collection is null
     */
    public ROHashSetBuilder(Collection<? extends E> c)
    { super(c); }

    /**
     * Constructs a new, empty {@code ROHashSetBuilder}; the backing {@code HashMap} instance has
     * the specified initial capacity and the specified load factor.
     *
     * <BR /><BR />To create a {@code ROHashSetBuilder} with an initial capacity that accommodates
     * an expected number of elements, use {@link #newROHashSetBuilder(int) newROHashSetBuilder}.
     *
     * @param initialCapacity the initial capacity of the hash map
     * @param loadFactor the load factor of the hash map
     * 
     * @throws IllegalArgumentException if the initial capacity is less than zero, or if the load
     * factor is nonpositive
     */
    public ROHashSetBuilder(int initialCapacity, float loadFactor)
    { super(initialCapacity, loadFactor); }

    /**
     * Constructs a new, empty {@code ROHashSetBuilder}; the backing {@code HashMap} instance has
     * the specified initial capacity and default load factor (0.75).
     *
     * <BR /><BR />To create a {@code ReadOnlyHashSet} with an initial capacity that accommodates
     * an expected number of elements, use {@link #newROHashSetBuilder(int) newROHashSetBuilder}.
     *
     * @param initialCapacity the initial capacity of the hash table
     * @throws IllegalArgumentException if the initial capacity is less than zero
     */
    public ROHashSetBuilder(int initialCapacity)
    { super(initialCapacity); }

    /**
     * Creates a new, empty {@code ROHashSetBuilder} suitable for the expected number of elements.
     * The returned set uses the default load factor of 0.75, and its initial capacity is generally
     * large enough so that the expected number of elements can be added without resizing the set.
     * 
     * @param <T> the type of elements maintained by the new set builder
     * @param numElements the expected number of elements
     * @return the newly created builder
     * @throws IllegalArgumentException if numElements is negative
     */
    public static <T> ROHashSetBuilder<T> newROHashSetBuilder(int numElements)
    {
        if (numElements < 0)
            throw new IllegalArgumentException("Negative number of elements: " + numElements);

        return new ROHashSetBuilder<>(calculateHashMapCapacity(numElements));
    }

    // Copied from JDK-21, java.util.HashMap
    // Calculate initial capacity for HashMap based classes, from expected size and default load
    // factor (0.75).

    private static int calculateHashMapCapacity(int numMappings)
    { return (int) Math.ceil(numMappings / (double) /* DEFAULT_LOAD_FACTOR */ 0.75f); }


    // ********************************************************************************************
    // ********************************************************************************************
    // Original JDK Methods
    // ********************************************************************************************
    // ********************************************************************************************


    public RemoveUnsupportedIterator<E> iterator()
    { return new RemoveUnsupportedIterator<>(super.iterator()); }

    /**
     * Adds the specified element to this set if it is not already present.  More formally, adds
     * the specified element {@code e} to this set if this set contains no element {@code e2} such
     * that {@code Objects.equals(e, e2)}.  If this set already contains the element, the call
     * leaves the set unchanged and returns {@code FALSE}.
     * 
     * <EMBED DATA-TYPE=HashSet CLASS='external-html' DATA-FILE-ID=MUTATOR>
     *
     * @param e element to be added to this set
     * @return {@code TRUE} if this set did not already contain the specified element
     */
    public boolean add(E e)
    {
        if (this.built) throw new AttemptedModificationException(ROHS);
        return super.add(e);
    }

    /**
     * Removes the specified element from this set if it is present.  More formally, removes an
     * element {@code e} such that {@code Objects.equals(o, e)}, if this set contains such an
     * element.  Returns {@code TRUE} if this set contained the element (or equivalently, if this
     * set changed as a result of the call).  (This set will not contain the element once the call
     * returns.)
     * 
     * <EMBED DATA-TYPE=HashSet CLASS='external-html' DATA-FILE-ID=MUTATOR>
     *
     * @param o object to be removed from this set, if present
     * @return {@code TRUE} if the set contained the specified element
     */
    public boolean remove(Object o)
    {
        if (this.built) throw new AttemptedModificationException(ROHS);
        return super.remove(o);
    }

    /**
     * Removes all of the elements from this set.  The set will be empty after this call returns.
     * <EMBED DATA-TYPE=HashSet CLASS='external-html' DATA-FILE-ID=MUTATOR>
     */
    public void clear()
    {
        if (this.built) throw new AttemptedModificationException(ROHS);
        super.clear();
    }


    // ********************************************************************************************
    // ********************************************************************************************
    // Methods inherited from class java.util.HashSet
    // ********************************************************************************************
    // ********************************************************************************************


    // contains, isEmpty, size, spliterator
    // 
    // Introspection Only: contains, isEmpty, size, spliterator
    // Mutator or Potential Mutator Methods: NONE
    // 
    // *** OTHER INHERITED METHODS ***
    // 
    // Methods inherited from class java.util.AbstractSet:
    // hashCode, removeAll
    // 
    // Methods inherited from class java.util.AbstractCollection:
    // addAll, containsAll, retainAll, toArray, toArray, toString
    // 
    // Methods inherited from interface java.util.Collection: 
    // parallelStream, removeIf, stream, toArray
    // 
    // Methods inherited from interface java.lang.Iterable:
    // forEach
    // 
    // Methods inherited from interface java.util.Set:
    // addAll, containsAll, hashCode, removeAll, retainAll, toArray, toArray

    @Override
    public boolean removeAll(Collection<?> c)
    {
        if (this.built) throw new AttemptedModificationException(ROHS);
        return super.removeAll(c);
    }

    @Override
    public boolean addAll(Collection<? extends E> c)
    {
        if (this.built) throw new AttemptedModificationException(ROHS);
        return super.addAll(c);
    }

    @Override
    public boolean retainAll(Collection<?> c)
    {
        if (this.built) throw new AttemptedModificationException(ROHS);
        return super.retainAll(c);
    }

    @Override
    public boolean removeIf(Predicate<? super E> filter)
    {
        if (this.built) throw new AttemptedModificationException(ROHS);
        return super.removeIf(filter);
    }


    // ********************************************************************************************
    // ********************************************************************************************
    // java.lang.Object & Cloneable
    // ********************************************************************************************
    // ********************************************************************************************


    /**
     * Compares the specified Object with this Builder for equality, as per the definition in the
     * original class {@code java.util.HashSet}.  Ignores the private field {@code 'built'}.  If
     * {@code 'this'} has not been built, but {@code 'o'} has been, that fact is ignored during the
     * equality-comparison.
     *
     * @param  o object to be compared for equality with this {@code ROHashSetBuilder} instance
     * @return true if the specified Object is equal to this Builder
     */
    public boolean equals(Object o)
    {
        if (this == o) return true;
        if (! (o instanceof ROHashSetBuilder)) return false;
        return super.equals((HashSet) o);
    }

    /**
     * Clones this instance' of {@code ROHashSetBuilder}.
     * 
     * <BR /><BR />The clone that's returned has had it's internal {@code 'built'} boolean-flag set
     * {@code FALSE}
     * 
     * @return a clone of this builder
     */
    public synchronized ROHashSetBuilder<E> clone()
    { return new ROHashSetBuilder<>(this); }

    private ROHashSetBuilder(ROHashSetBuilder<E> rohsb)
    { super(rohsb); this.built=false; }
}