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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
/*
 * Copyright (c) 1997, 2018, 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.function.Predicate;
import java.util.function.UnaryOperator;

import java.util.*;

import java.io.Serializable;

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


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

    // Exception messages need this
    private static final String ROAL = "ArrayList";

    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 ArrayList} to the 
     * {@code ReadOnlyArrayList} Wrapper-Class.
     * 
     * @return a newly constructed {@code ReadOnlyArrayList} "Wrapper-Class", shielding the
     * internal {@code 'arrayList'} private-field from any modification.
     */
    public ReadOnlyArrayList<E> build()
    {
        super.trimToSize();
        this.built = true;

        return (size() == 0)
            ? ReadOnlyArrayList.emptyROAL()
            : new ReadOnlyArrayList<>(this, friendClassBadge);
    }


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


    /**
     * Constructs an empty {@code ROArrayListBuilder} with the specified initial capacity.
     * @param  initialCapacity  the initial capacity of the list
     * @throws IllegalArgumentException if the specified initial capacity is negative
     */
    public ROArrayListBuilder(int initialCapacity)
    { super(initialCapacity); }

    /** Constructs an empty list with an initial capacity of ten. */
    public ROArrayListBuilder()
    { super(); }

    /**
     * Constructs a {@code ROArrayListBuilder} containing the elements of the specified collection,
     * in the order they are returned by the collection's iterator.
     *
     * @param c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public ROArrayListBuilder(Collection<? extends E> c)
    { super(c); }


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


    /**
     * Trims the capacity of this {@code ArrayList} instance to be the list's current size.  An
     * application can use this operation to minimize the storage of an {@code ArrayList} instance.
     * 
     * <EMBED DATA-TYPE=ArrayList CLASS='external-html' DATA-FILE-ID=MUTATOR>
     */
    public void trimToSize()
    {
        if (this.built) throw new AttemptedModificationException(ROAL);
        super.trimToSize(); 
    }

    /**
     * Increases the capacity of this {@code ArrayList} instance, if necessary, to ensure that it
     * can hold at least the number of elements specified by the minimum capacity argument.
     * 
     * <EMBED DATA-TYPE=ArrayList CLASS='external-html' DATA-FILE-ID=MUTATOR>
     *
     * @param minCapacity the desired minimum capacity
     */
    public void ensureCapacity(int minCapacity)
    {
        if (this.built) throw new AttemptedModificationException(ROAL);
        super.ensureCapacity(minCapacity); 
    }

    /**
     * Replaces the element at the specified position in this list with the specified element.
     * 
     * <EMBED DATA-TYPE=ArrayList CLASS='external-html' DATA-FILE-ID=MUTATOR>
     * 
     * @param index index of the element to replace
     * @param element element to be stored at the specified position
     * @return the element previously at the specified position
     * 
     * @throws IndexOutOfBoundsException if the index is out of range
     * {@code (index < 0 || index > size())}
     */
    public E set(int index, E element)
    {
        if (this.built) throw new AttemptedModificationException(ROAL);
        return super.set(index, element); 
    }

    /**
     * Appends the specified element to the end of this list.
     * <EMBED DATA-TYPE=ArrayList CLASS='external-html' DATA-FILE-ID=MUTATOR>
     * @param e element to be appended to this list
     * @return {@code TRUE} (as specified by {@code Collection.add})
     */
    public boolean add(E e)
    {
        if (this.built) throw new AttemptedModificationException(ROAL);
        return super.add(e); 
    }

    /**
     * Inserts the specified element at the specified position in this list. Shifts the element
     * currently at that position (if any) and any subsequent elements to the right (adds one to
     * their indices).
     * 
     * <EMBED DATA-TYPE=ArrayList CLASS='external-html' DATA-FILE-ID=MUTATOR>
     *
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * 
     * @throws IndexOutOfBoundsException if the index is out of range
     * {@code (index < 0 || index >= size())}
     */
    public void add(int index, E element)
    {
        if (this.built) throw new AttemptedModificationException(ROAL);
        super.add(index, element); 
    }

    /**
     * Removes the element at the specified position in this list.  Shifts any subsequent elements
     * to the left (subtracts one from their indices).
     * 
     * <EMBED DATA-TYPE=ArrayList CLASS='external-html' DATA-FILE-ID=MUTATOR>
     * 
     * @param index the index of the element to be removed
     * @return the element that was removed from the list
     * 
     * @throws IndexOutOfBoundsException if the index is out of range
     * {@code (index < 0 || index >= size())}
     */
    public E remove(int index)
    {
        if (this.built) throw new AttemptedModificationException(ROAL);
        return super.remove(index); 
    }

    /**
     * Removes the first occurrence of the specified element from this list, if it is present.  If
     * the list does not contain the element, it is unchanged.  More formally, removes the element
     * with the lowest index {@code i} such that {@code Objects.equals(o, get(i))} (if such an
     * element exists).  Returns {@code TRUE} if this list contained the specified element (or
     * equivalently, if this list changed as a result of the call).
     * 
     * <EMBED DATA-TYPE=ArrayList CLASS='external-html' DATA-FILE-ID=MUTATOR>
     *
     * @param o element to be removed from this list, if present
     * @return {@code TRUE} if this list contained the specified element
     */
    public boolean remove(Object o)
    {
        if (this.built) throw new AttemptedModificationException(ROAL);
        return super.remove(o); 
    }

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

    /**
     * Appends all of the elements in the specified collection to the end of this list, in the
     * order that they are returned by the specified collection's Iterator.  The behavior of this
     * operation is undefined if the specified collection is modified while the operation is in
     * progress.  (This implies that the behavior of this call is undefined if the specified
     * collection is this list, and this list is nonempty.)
     * 
     * <EMBED DATA-TYPE=ArrayList CLASS='external-html' DATA-FILE-ID=MUTATOR>
     * 
     * @param c collection containing elements to be added to this list
     * @return {@code TRUE} if this list changed as a result of the call
     * @throws NullPointerException if the specified collection is null
     */
    public boolean addAll(Collection<? extends E> c)
    {
        if (this.built) throw new AttemptedModificationException(ROAL);
        return super.addAll(c); 
    }

    /**
     * Inserts all of the elements in the specified collection into this list, starting at the
     * specified position.  Shifts the element currently at that position (if any) and any
     * subsequent elements to the right (increases their indices).  The new elements will appear in
     * the list in the order that they are returned by the specified collection's iterator.
     * 
     * <EMBED DATA-TYPE=ArrayList CLASS='external-html' DATA-FILE-ID=MUTATOR>
     *
     * @param index index at which to insert the first element from the specified collection
     * @param c collection containing elements to be added to this list
     * @return {@code TRUE} if this list changed as a result of the call
     * @throws NullPointerException if the specified collection is null
     * 
     * @throws IndexOutOfBoundsException if the index is out of range
     * {@code (index < 0 || index > size())}
     */
    public boolean addAll(int index, Collection<? extends E> c)
    {
        if (this.built) throw new AttemptedModificationException(ROAL);
        return super.addAll(index, c); 
    }

    /**
     * Removes from this list all of its elements that are contained in the specified collection.
     * 
     * <EMBED DATA-TYPE=ArrayList CLASS='external-html' DATA-FILE-ID=MUTATOR>
     * 
     * @param c collection containing elements to be removed from this list
     * @return {@code TRUE} if this list changed as a result of the call
     * 
     * @throws ClassCastException if the class of an element of this list is incompatible with the
     * specified collection
     * (<a href="Collection.html#optional-restrictions">optional</a>)
     * 
     * @throws NullPointerException if this list contains a null element and the specified
     * collection does not permit null elements
     * (<a href="Collection.html#optional-restrictions">optional</a>),
     * or if the specified collection is null
     * 
     * @see ReadOnlyCollection#contains(Object)
     */
    public boolean removeAll(Collection<?> c)
    {
        if (this.built) throw new AttemptedModificationException(ROAL);
        return super.removeAll(c); 
    }

    /**
     * Retains only the elements in this list that are contained in the specified collection.  In
     * other words, removes from this list all of its elements that are not contained in the
     * specified collection.
     * 
     * <EMBED DATA-TYPE=ArrayList CLASS='external-html' DATA-FILE-ID=MUTATOR>
     *
     * @param c collection containing elements to be retained in this list
     * @return {@code TRUE} if this list changed as a result of the call
     * 
     * @throws ClassCastException if the class of an element of this list is incompatible with the
     * specified collection
     * (<a href="Collection.html#optional-restrictions">optional</a>)
     * 
     * @throws NullPointerException if this list contains a null element and the specified
     * collection does not permit null elements
     * (<a href="Collection.html#optional-restrictions">optional</a>),
     * or if the specified collection is null
     * 
     * @see ReadOnlyCollection#contains(Object)
     */
    public boolean retainAll(Collection<?> c)
    {
        if (this.built) throw new AttemptedModificationException(ROAL);
        return super.retainAll(c); 
    }

    /**
     * Removes all of the elements of this collection that satisfy the given predicate. Errors or
     * runtime exceptions thrown during iteration or by the predicate are relayed to the caller.
     * 
     * <EMBED DATA-TYPE=ArrayList CLASS='external-html' DATA-FILE-ID=MUTATOR>
     * 
     * @param filter a predicate which returns true for elements to be removed
     * @return {@code TRUE} if any elements were removed
     * @throws NullPointerException If parameter {@code 'filter'} has been passed null.
     */
    public boolean removeIf(Predicate<? super E> filter)
    {
        if (this.built) throw new AttemptedModificationException(ROAL);
        return super.removeIf(filter); 
    }

    /**
     * Replaces each element of this list with the result of applying the operator to that element.
     * Errors or runtime exceptions thrown by the operator are relayed to the caller.
     * 
     * <EMBED DATA-TYPE=ArrayList CLASS='external-html' DATA-FILE-ID=MUTATOR>
     * 
     * @param operator the operator to apply to each element
     * 
     * @throws NullPointerException - if the specified operator is null or if the operator result
     * is a null value and this list does not permit null elements (optional)
     */
    public void replaceAll(UnaryOperator<E> operator)
    {
        if (this.built) throw new AttemptedModificationException(ROAL);
        super.replaceAll(operator); 
    }

    /**
     * Sorts this list according to the order induced by the specified Comparator. The sort is
     * stable: this method must not reorder equal elements.
     * 
     * <BR /><BR />All elements in this list must be mutually comparable using the specified
     * comparator (that is, {@code c.compare(e1, e2)} must not throw a {@code ClassCastException}
     * for any elements e1 and e2 in the list).
     * 
     * <BR /><BR />If the specified comparator is null then all elements in this list must
     * implement the Comparable interface and the elements' natural ordering should be used.
     * 
     * <BR /><BR />This list must be modifiable, but need not be resizable.
     * 
     * <EMBED DATA-TYPE=ArrayList CLASS='external-html' DATA-FILE-ID=MUTATOR>
     * 
     * @param c the Comparator used to compare list elements. A null value indicates that the
     * elements' natural ordering should be used
     * 
     * @throws ClassCastException if the list contains elements that are not mutually comparable
     * using the specified comparator
     * 
     * @throws IllegalArgumentException  (optional) if the comparator is found to violate the
     * {@code Comparator} contract
     */
    public void sort(Comparator<? super E> c)
    {
        if (this.built) throw new AttemptedModificationException(ROAL);
        super.sort(c); 
    }


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


    // clone, forEach, hashCode, iterator, listIterator, listIterator, removeRange, spliterator,
    // subList, toArray, toArray
    //
    // Introspection Only:              clone, forEach, hashCode, spliterator, toArray, toArray
    // Mutator or Potential Mutator:    ilterator, listIterator, listIterator, subList
    // Protected (not-needed) Mutator:  removeRange
    //
    // *** OTHER INHERITED METHODS - ALL READ-ONLY METHODS ***
    //
    // Methods inherited from class java.util.AbstractCollection:   containsAll, toString
    // Methods inherited from interface java.util.Collection:       parallelStream, stream, toArray
    // Methods inherited from interface java.util.List:             containsAll

    /**
     * Restricts a back-door into the underlying data-structure.
     * <EMBED CLASS='external-html'DATA-RET_TYPE=Iterator DATA-FILE-ID=UNMODIFIABLE>
     * @return a {@code java.util.Iterator} that cannot modify this {@code ArrayList-Builder}
     */
    public RemoveUnsupportedIterator<E> iterator()
    { return new RemoveUnsupportedIterator<>(super.iterator()); }

    /**
     * Restricts a back-door into the underlying data-structure.
     * <EMBED CLASS='external-html'DATA-RET_TYPE=ListIterator DATA-FILE-ID=UNMODIFIABLE>
     * @return a {@code java.util.ListIterator} that cannot modify this {@code ArrayList-Builder}
     */
    public ListIterator<E> listIterator()
    { return ROHelpers.removeUnsupportedListIterator(super.listIterator()); }

    ListIterator<E> _listIterator(ReadOnlyArrayList.AccessBadge friendClassBadge)
    { return super.listIterator(); }

    /**
     * Restricts a back-door into the underlying data-structure.
     * <EMBED CLASS='external-html'DATA-RET_TYPE=ListIterator DATA-FILE-ID=UNMODIFIABLE>
     * @return a {@code java.util.ListIterator} that cannot modify this {@code ArrayList-Builder}
     */
    public ListIterator<E> listIterator(int index)
    { return ROHelpers.removeUnsupportedListIterator(super.listIterator(index)); }

    ListIterator<E> _listIterator(int index, ReadOnlyArrayList.AccessBadge friendClassBadge)
    { return super.listIterator(index); }

    /**
     * Restricts a back-door into the underlying data-structure.
     * <EMBED CLASS='external-html'DATA-RET_TYPE=List DATA-FILE-ID=UNMODIFIABLE>
     * @return a {@code java.util.List} that cannot modify this {@code ArrayList-Builder}
     */
    public List<E> subList(int fromIndex, int toIndex)
    { return Collections.unmodifiableList(super.subList(fromIndex, toIndex)); }

    List<E> _subList(int fromIndex, int toIndex, ReadOnlyArrayList.AccessBadge friendClassBadge)
    { return super.subList(fromIndex, toIndex); }


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


    /**
     * Compares the specified Object with this Builder for equality, as per the definition in the
     * original class {@code java.util.ArrayList}.  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 ROArrayListBuilder} 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 ROArrayListBuilder)) return false;
        return super.equals((ArrayList) o);
    }

    /**
     * Clones this instance' of {@code ROArrayListBuilder}.
     * 
     * <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 ROArrayListBuilder<E> clone()
    { return new ROArrayListBuilder<>(this); }

    private ROArrayListBuilder(ROArrayListBuilder<E> roalb)
    { super(roalb); this.built=false; }
}