-
Notifications
You must be signed in to change notification settings - Fork 226
Expand file tree
/
Copy pathAbstractArray.java
More file actions
596 lines (542 loc) · 21.3 KB
/
AbstractArray.java
File metadata and controls
596 lines (542 loc) · 21.3 KB
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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
package org.python.core;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.Arrays;
/**
* Abstract class that manages bulk structural and data operations
* on arrays, defering type-specific element-wise operations to the
* subclass. Subclasses supply the underlying array and the
* type-specific operations--greatly reducing the need for casting
* (thus achieving array-like performances with collection-like
* flexibility). Also includes
* functionality to support integration with the the jdk's
* collections (via methods that return a modification increment).<P>
* Subclasses will want to provide the following methods (which are
* not declared in this class since subclasses should specify the
* explicit return type):
* <UL>
* <LI><CODE><type> get(int)</CODE></LI>
* <LI><CODE>void set(int, <type>)</CODE></LI>
* <LI><CODE>void add(<type>)</CODE></LI>
* <LI><CODE>void add(int, <type>)</CODE></LI>
* <LI><CODE><type>[] toArray()</CODE></LI>
* </UL><P>
* Clone cannot be supported since the array is not held locally.
* But the @link #AbstractArray(AbstractArray) constructor can be used
* for suclasses that need to support clone.
* <P>
* This "type-specific collections" approach was originally developed
* by Dennis Sosnoski, who provides a more complete library at the
* referenced URL. Sosnoski's library does not integrate with the
* jdk collection classes but provides collection-like classes.
*
* @author Clark Updike
* @see <A href="http://www.sosnoski.com/opensrc/tclib/index.html">
* Sosnoski's Type-Specific Collection Library</A>
*/
public abstract class AbstractArray implements Serializable{
/**
* Size of the current array, which can be larger than the
* <CODE>size</CODE> field.
*/
protected int capacity;
/**
* The number of values currently present in the array.
*/
protected int size;
/**
* The modification count increment indicates if a structural change
* occurred as a result of an operation that would make concurrent iteration
* over the array invalid. It is typically used by subclasses that
* extend <CODE>AbstractList</CODE>, by adding the value to
* <CODE>AbstractList.modCount</CODE> after performing a potentially
* structure-altering operation. A value of 0 indicates that
* it is still valid to iterate over the array. A value of 1
* indicates it is no longer valid to iterate over the range.<P>
* This class uses a somewhat stricter semantic for <CODE>modCount</CODE>.
* Namely, <CODE>modCountIncr</CODE> is only set to 1 if a structural
* change occurred. The jdk collections generally increment
* <CODE>modCount</CODE> if a potentially structure-altering method
* is called, regardless of whether or not a change actually occurred.
*
* <b>See also:</b> <code>java.util.AbstractList#modCount</code>
*/
protected int modCountIncr;
/**
* Since AbstractArray can support a clone method, this facilitates subclasses that want to
* implement clone (poor man's cloning). Subclasses can then do this:
*
* <pre>{@literal
* public MyManagedArray(MyManagedArray toCopy) {
* super(this);
* this.baseArray = (<my array type>) toCopy.copyArray();
* this.someProp = toCopy.someProp;
* <etc>
* }
*
* public Object clone() {
* return new MyManagedArray(this);
* }
* }</pre>
*
* @param toCopy
*/
public AbstractArray(AbstractArray toCopy) {
this.capacity = toCopy.capacity;
// let modCountIncr default to 0
this.size = toCopy.size;
}
/**
* Use when the subclass has a preexisting array.
*
* @param size the initial size of the array
*/
public AbstractArray(int size) {
this.size = size;
this.capacity = size;
}
/**
* Creates the managed array with a default size of 10.
*
* @param type array element type (primitive type or object class)
*/
public AbstractArray(Class type) {
this(type, 10);
}
/**
* Construtor for multi-dimensional array types.
* For example, <CODE>char[][]</CODE>. This class only manages the
* top level dimension of the array. For single dimension
* arrays (the more typical usage), use the other constructors.<P>
*
* @param type Array element type (primitive type or object class).
* @param dimensions An int array specifying the dimensions. For
* a 2D array, something like <CODE>new int[] {10,0}</CODE> to
* create 10 elements each of which can hold an reference to an
* array of the same type.
* @see Array#newInstance(java.lang.Class, int[])
*/
public AbstractArray(Class type, int[] dimensions) {
Object array = Array.newInstance(type, dimensions);
this.capacity = dimensions[0];
setArray(array);
}
/**
* Creates the managed array with the specified size.
*
* @param type array element type (primitive type or object class)
* @param size number of elements initially allowed in array
*/
public AbstractArray(Class type, int size) {
Object array = Array.newInstance(type, size);
this.capacity = Math.max(size, 10);
setArray(array);
}
/**
* Appends the supplied array, which must be an array of the same
* type as <CODE>this</CODE>, to the end of <CODE>this</CODE>.
* <P><CODE>AbstractList</CODE> subclasses should update their
* <CODE>modCount</CODE> after calling this method.
*
* @param ofArrayType the array to append
*/
public void appendArray(Object ofArrayType) {
replaceSubArray(ofArrayType, this.size);
}
/**
* Set the array to the empty state, clearing all the data out and
* nulling objects (or "zero-ing" primitives).
* <P>Note: This method does not set <CODE>modCountIncr</CODE> to
* <CODE>1</CODE> even though <CODE>java.util.ArrayList</CODE>
* would.
*
* <P><CODE>AbstractList</CODE> subclasses should update their
* <CODE>modCount</CODE> after calling this method.
*/
public void clear() {
this.modCountIncr = 0;
if (this.size != 0) {
this.modCountIncr = 1;
clearRange(0, this.size);
setSize(0);
}
}
/**
* Clears out the values in the specified range. For object arrays,
* the cleared range is nullified. For primitve arrays, it is
* "zero-ed" out.
* <P>Note: This method does not set <CODE>modCountIncr</CODE> to
* <CODE>1</CODE> even though <CODE>java.util.ArrayList</CODE>
* would.
*
* @param start the start index, inclusive
* @param stop the stop index, exclusive
*/
protected void clearRange(int start, int stop) {
if (start < stop && start >= 0 && stop <= this.size) {
clearRangeInternal(start, stop);
} else {
if (start == stop && start >= 0 && stop <= this.size) {
return;
}
throw new ArrayIndexOutOfBoundsException("start and stop must follow: 0 <= start <= stop <= " +
(this.size) + ", but found start= " + start + " and stop=" + stop);
}
}
/**
* Used internally, no bounds checking.
*
* @param start the start index, inclusive
* @param stop the stop index, exclusive
*/
private void clearRangeInternal(int start, int stop) {
Object base = getArray();
Class arrayType = base.getClass().getComponentType();
if (arrayType.isPrimitive()) {
if (arrayType == Boolean.TYPE) {
Arrays.fill((boolean[]) base, start, stop, false);
} else if (arrayType == Character.TYPE) {
Arrays.fill((char[]) base, start, stop, '\u0000');
} else if (arrayType == Byte.TYPE) {
Arrays.fill((byte[]) base, start, stop, (byte) 0);
} else if (arrayType == Short.TYPE) {
Arrays.fill((short[]) base, start, stop, (short) 0);
} else if (arrayType == Integer.TYPE) {
Arrays.fill((int[]) base, start, stop, 0);
} else if (arrayType == Long.TYPE) {
Arrays.fill((long[]) base, start, stop, 0);
} else if (arrayType == Float.TYPE) {
Arrays.fill((float[]) base, start, stop, 0.f);
} else if (arrayType == Double.TYPE) {
Arrays.fill((double[]) base, start, stop, 0.);
}
} else {
Arrays.fill((Object[]) base, start, stop, null);
}
}
/**
* Constructs and returns a simple array containing the same data as held
* in this growable array.
*
* @return array containing a shallow copy of the data.
*/
public Object copyArray() {
Object copy = createArray(this.size);
System.arraycopy(getArray(), 0, copy, 0, this.size);
return copy;
}
/**
* Ensures that the base array has at least the specified
* minimum capacity.
* <P><CODE>AbstractList</CODE> subclasses should update their
* <CODE>modCount</CODE> after calling this method.
*
* @param minCapacity new minimum size required
*/
protected void ensureCapacity(int minCapacity) {
// ArrayList always increments the mod count, even if no
// structural change is made (not sure why).
// This only indicates a mod count change if a change is made.
this.modCountIncr = 0;
if (minCapacity > this.capacity) {
this.modCountIncr = 1;
int newCapacity = (this.capacity * 2) + 1;
newCapacity = (newCapacity < minCapacity)
? minCapacity
: newCapacity;
setNewBase(newCapacity);
this.capacity = newCapacity;
}
}
/**
* Gets the next add position for appending a value to those in the array.
* If the underlying array is full, it is grown by the appropriate size
* increment so that the index value returned is always valid for the
* array in use by the time of the return.
* <P><CODE>AbstractList</CODE> subclasses should update their
* <CODE>modCount</CODE> after calling this method.
*
* @return index position for next added element
*/
protected int getAddIndex() {
int index = this.size++;
if (this.size > this.capacity) {
ensureCapacity(this.size);
}
return index;
}
/**
* Get the backing array. This method is used by the type-agnostic base
* class code to access the array used for type-specific storage by the
* child class.
*
* @return backing array object
*/
protected abstract Object getArray();
protected boolean isEmpty() {
return this.size == 0;
}
/**
* Makes room to insert a value at a specified index in the array.
* <P><CODE>AbstractList</CODE> subclasses should update their
* <CODE>modCount</CODE> after calling this method. Does not change
* the <CODE>size</CODE> property of the array.
*
* @param index index position at which to insert element
*/
protected void makeInsertSpace(int index) {
makeInsertSpace(index, 1);
}
protected void makeInsertSpace(int index, int length) {
this.modCountIncr = 0;
if (index >= 0 && index <= this.size) {
int toCopy = this.size - index;
this.size = this.size + length;
// First increase array size if needed
if (this.size > this.capacity) {
ensureCapacity(this.size);
}
if (index < this.size - 1) {
this.modCountIncr = 1;
Object array = getArray();
System.arraycopy(array, index, array, index + length, toCopy);
}
} else {
throw new ArrayIndexOutOfBoundsException("Index must be between 0 and " +
this.size + ", but was " + index);
}
}
/**
* Remove a value from the array. All values above the index removed
* are moved down one index position.
* <P><CODE>AbstractList</CODE> subclasses should always increment
* their <CODE>modCount</CODE> method after calling this, as
* <CODE>remove</CODE> always causes a structural modification.
*
* @param index index number of value to be removed
*/
public void remove(int index) {
if (index >= 0 && index < this.size) {
this.size = this.size - 1;
if (index < this.size) {
Object base = getArray();
System.arraycopy(base, index + 1, base, index, this.size - index);
clearRangeInternal(this.size, this.size);
}
} else {
if (this.size == 0) {
throw new IllegalStateException("Cannot remove data from an empty array");
}
throw new IndexOutOfBoundsException("Index must be between 0 and " +
(this.size - 1) + ", but was " + index);
}
}
/**
* Removes a range from the array at the specified indices.
* @param start inclusive
* @param stop exclusive
*/
public void remove(int start, int stop) {
if (start >= 0 && stop <= this.size && start <= stop) {
Object base = getArray();
int nRemove = stop - start;
if (nRemove == 0) {
return;
}
System.arraycopy(base, stop, base, start, this.size - stop);
this.size = this.size - nRemove;
clearRangeInternal(this.size, this.size + nRemove);
setArray(base);
return;
}
throw new IndexOutOfBoundsException("start and stop must follow: 0 <= start <= stop <= " +
this.size + ", but found start= " + start + " and stop=" + stop);
}
/**
* Allows an array type to overwrite a segment of the array.
* Will expand the array if <code>(atIndex + 1) + ofArrayType</code>'s length
* is greater than the current length.
* <P><CODE>AbstractList</CODE> subclasses should update their
* <CODE>modCount</CODE> after calling this method.
*
* @param array
* @param atIndex
*/
public void replaceSubArray(Object array, int atIndex) {
int arrayLen = Array.getLength(array);
replaceSubArray(atIndex, Math.min(this.size, atIndex + arrayLen), array, 0, arrayLen);
}
/**
* Replace a range of this array with another subarray.
* @param thisStart the start index (inclusive) of the subarray in this
* array to be replaced
* @param thisStop the stop index (exclusive) of the subarray in this
* array to be replaced
* @param srcArray the source array from which to copy
* @param srcStart the start index (inclusive) of the replacement subarray
* @param srcStop the stop index (exclusive) of the replacement subarray
*/
public void replaceSubArray(int thisStart, int thisStop, Object srcArray,
int srcStart, int srcStop) {
this.modCountIncr = 0;
if (!srcArray.getClass().isArray()) {
throw new IllegalArgumentException("'array' must be an array type");
}
int replacedLen = thisStop - thisStart;
if (thisStart < 0 || replacedLen < 0 || thisStop > this.size) {
String message = null;
if (thisStart < 0) {
message = "thisStart < 0 (thisStart = " + thisStart + ")";
} else if (replacedLen < 0) {
message = "thisStart > thistStop (thisStart = " + thisStart +
", thisStop = " + thisStop + ")";
} else if (thisStop > this.size) {
message = "thisStop > size (thisStop = " + thisStop +
", size = " + this.size + ")";
} else {
throw new InternalError("Incorrect validation logic");
}
throw new ArrayIndexOutOfBoundsException(message);
}
int srcLen = Array.getLength(srcArray);
int replacementLen = srcStop - srcStart;
if (srcStart < 0 || replacementLen < 0 || srcStop > srcLen) {
String message = null;
if (srcStart < 0) {
message = "srcStart < 0 (srcStart = " + srcStart +")";
} else if (replacementLen < 0) {
message = "srcStart > srcStop (srcStart = " + srcStart +
", srcStop = " + srcStop + ")";
} else if (srcStop > srcLen) {
message = "srcStop > srcArray length (srcStop = " + srcStop +
", srcArray length = " +srcLen + ")";
} else {
throw new InternalError("Incorrect validation logic");
}
throw new IllegalArgumentException("start, stop and array must follow:\n\t"
+ "0 <= start <= stop <= array length\nBut found\n\t" +
message);
}
int lengthChange = replacementLen - replacedLen;
// Adjust array size if needed.
if (lengthChange < 0) {
remove(thisStop + lengthChange, thisStop);
} else if (lengthChange > 0) {
makeInsertSpace(thisStop, lengthChange);
}
try {
this.modCountIncr = 1;
System.arraycopy(srcArray, srcStart, getArray(), thisStart, replacementLen);
} catch (ArrayStoreException e) {
throw new IllegalArgumentException("'ofArrayType' must be compatible with existing array type of " +
getArray().getClass().getName() + "\tsee java.lang.Class.getName().");
}
}
/**
* Set the backing array. This method is used by the type-agnostic base
* class code to set the array used for type-specific storage by the
* child class.
*
* @param array the backing array object
*/
protected abstract void setArray(Object array);
/**
* Replaces the existing base array in the subclass with a new
* base array resized to the specified capacity.
*
* @param newCapacity
*/
private void setNewBase(int newCapacity) {
this.modCountIncr = 1;
Object base = getArray();
Object newBase = createArray(newCapacity);
System.arraycopy(base, 0, newBase, 0, capacity > newCapacity ? newCapacity : capacity);
setArray(newBase);
}
/**
* Sets the number of values currently present in the array. If the new
* size is greater than the current size, the added values are initialized
* to the default values. If the new size is less than the current size,
* all values dropped from the array are discarded.
* <P><CODE>AbstractList</CODE> subclasses should update their
* <CODE>modCount</CODE> after calling this method.
*
* @param count number of values to be set
*/
public void setSize(int count) {
if (count > this.capacity) {
ensureCapacity(count);
} else if (count < this.size) {
clearRange(count, this.size);
}
this.size = count;
}
/**
* Get the number of values currently present in the array.
*
* @return count of values present
*/
public int getSize() {
return this.size;
}
/**
* Provides a default comma-delimited representation of array.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append("[");
Object base = getArray();
Class arrayType = base.getClass().getComponentType();
int n = this.size - 1;
if (arrayType.isPrimitive()) {
for (int i = 0; i < n; i++) {
buf.append(Array.get(base, i)).append(", ");
}
if (n >= 0) {
buf.append(Array.get(base, n));
}
} else {
Object[] objects = (Object[]) base;
for (int i = 0; i < n; i++) {
buf.append(objects[i]).append(", ");
}
if (n >= 0) {
buf.append(objects[n]);
}
}
buf.append("]");
return buf.toString();
}
/**
* Removes any excess capacity in the backing array so it is
* just big enough to hold the amount of data actually in the array.
*/
protected void trimToSize() {
// Don't need to adjust modCountIncr since AbstractList subclasses
// should only ever see up to the size (and not the capacity--which
// is encapsulated).
if (this.size < this.capacity) {
setNewBase(this.size);
}
}
/**
* Returns the modification count increment, which is used by
* <CODE>AbstractList</CODE> subclasses to adjust <CODE>modCount</CODE>
* <CODE>AbstractList</CODE> uses it's <CODE>modCount</CODE> field
* to invalidate concurrent operations (like iteration) that should
* fail if the underlying array changes structurally during the
* operation.
*
* @return the modification count increment (0 if no change, 1 if changed)
*/
public int getModCountIncr() {
return this.modCountIncr;
}
/**
* @return an array of the given size for the type used by this abstract array.
*/
protected abstract Object createArray(int size);
}