summaryrefslogtreecommitdiff
path: root/projects/net.wotonomy.foundation/src/main/java/net/wotonomy/foundation/NSArray.java
blob: 3b75868131fdf65b3456c64b6f55778825f635db (plain)
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
/*
Wotonomy: OpenStep design patterns for pure Java applications.
Copyright (C) 2000 Blacksmith, Inc.

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library 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
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, see http://www.gnu.org
*/

package net.wotonomy.foundation;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

/**
 * NSArray is an unmodifiable List. Calling the mutator methods of the List
 * interface (add, addAll, set, etc.) on an instance of NSArray will throw an
 * Unsupported Operation exception: use a NSMutableArray instead. This is to
 * simulate Objective-C's pattern of exposing mutator methods only on mutable
 * subinterface, which is wonderful for communicating via interface the contract
 * on returned collections (whether you may modify return values) as well as
 * implementing array faults.
 *
 * @author michael@mpowers.net
 * @author $Author: cgruber $
 * @version $Revision: 929 $
 */
public class NSArray<T> implements List<T>, Serializable {
	private static final long serialVersionUID = 3640615326084287961L;

	/**
	 * Actual list that backs this instance.
	 */
	List<T> list;

	/**
	 * Return value when array index is not found.
	 */
	public static final int NotFound = -1;

	/**
	 * A constant representing an empty array.
	 */
	public static final NSArray<?> EmptyArray = new NSArray<>();

	/**
	 * Returns an NSArray backed by the specified List. This is useful to "protect"
	 * an internal representation that is returned by a method of return type
	 * NSArray.
	 */
	public static <T> NSArray<T> arrayBackedByList(List<T> aList) {
		return new NSArray<>(aList, null);
	}

	/**
	 * A constructor that uses the provided list as the backing list object. This is
	 * unlike ArrayList and other java.util.Collection types insofar as that API
	 * requires that the provided Collection be copied into the newly constructed
	 * Collection.
	 * 
	 * TODO: See if this signature can be reasonably changed, as having a no-op
	 * parameter is a little counter-intuitive.
	 * 
	 * @param aList   A list that the caller wishes to become the backing list for
	 *                the NSArray.
	 * @param ignored This parameter is entirely ignored, and is only there to
	 *                distinguish the API.
	 */
	NSArray(List<T> aList, Object ignored) // differentiates
	{
		list = aList;
	}

	/**
	 * Constructor with a size hint, used by NSMutableArray.
	 */
	NSArray(int aSize) {
		list = new ArrayList<>(aSize);
	}

	/**
	 * Default constructor returns an empty array.
	 */
	public NSArray() {
		list = new ArrayList<>();
	}

	/**
	 * Produces an array containing only the specified object.
	 */
	public NSArray(T anObject) {
		this();
		list.add(anObject);
	}

	/**
	 * Produces an array containing the specified objects.
	 */
	public NSArray(T[] anArray) {
		this();
		for (int i = 0; i < anArray.length; i++) {
			list.add(anArray[i]);
		}
	}

	/**
	 * Produces an array containing the objects in the specified collection.
	 */
	public NSArray(Collection<T> aCollection) {
		this();
		Iterator<T> i = aCollection.iterator();
		while (i.hasNext())
			list.add(i.next());
	}

	/**
	 * Returns the number of items in this array.
	 */
	public int count() {
		return list.size();
	}

	/**
	 * Returns an array containing all objects in this array plus the specified
	 * object.
	 */
	public NSArray<T> arrayByAddingObject(T anObject) {
		NSArray<T> result = new NSArray<>(this);
		result.protectedAdd(anObject);
		return result;
	}

	/**
	 * Returns an array containing all objects in this array plus all objects in the
	 * specified list.
	 */
	public NSArray<T> arrayByAddingObjectsFromArray(Collection<T> aCollection) {
		NSArray<T> result = new NSArray<>(this);
		result.protectedAddAll(aCollection);
		return result;
	}

	/**
	 * Returns a string containing the string representations of each element in
	 * this array, with each element separated from each neighboring element by the
	 * specified string.
	 */
	public String componentsJoinedByString(String separator) {
		StringBuffer buf = new StringBuffer();
		Iterator<T> it = list.iterator();
		if (it.hasNext()) {
			buf.append(it.next().toString());
		}
		while (it.hasNext()) {
			buf.append(separator);
			buf.append(String.valueOf(it.next()));
		}
		return buf.toString();
	}

	/**
	 * Returns whether an equivalent object is contained in this array.
	 */
	public boolean containsObject(T anObject) {
		return list.contains(anObject);
	}

	/**
	 * Returns the first object in this array that is equivalent to an object in the
	 * specified list, or null if no objects are in common.
	 */
	public T firstObjectCommonWithArray(Collection<T> aCollection) {
		if (aCollection == null)
			return null;

		T o;
		Iterator<T> it = list.iterator();
		while (it.hasNext()) {
			o = it.next();
			if (aCollection.contains(o))
				return o;
		}
		return null;
	}

	/**
	 * Returns whether the specified list contains elements equivalent to those in
	 * this array in the same order.
	 */
	public boolean isEqualToArray(List<T> aList) {
		return list.equals(aList);
	}

	/**
	 * Returns the last object in this array, or null if the array is empty.
	 */
	public T lastObject() {
		int i;
		if ((i = list.size()) == 0)
			return null;
		return list.get(i - 1);
	}

	/**
	* 
	*/
	/*
	 * public NSArray sortedArrayUsingSelector (NSSelector);
	 */

	/**
	 * Returns an array comprised of only those elements whose indices fall within
	 * the specified range.
	 */
	public NSArray<T> subarrayWithRange(NSRange aRange) {
		// TODO: Test this logic.
		NSArray<T> result = new NSArray<>();
		if (aRange == null)
			return result;

		int loc = aRange.location();
		int max = aRange.maxRange();
		int count = count();
		for (int i = loc; i <= max && i < count; i++) {
			result.protectedAdd(list.get(i));
		}
		return result;
	}

	/**
	 * Returns an enumeration over the the elements of the array.
	 */
	public Enumeration<T> objectEnumerator() {
		// TODO: Test this logic.
		return new Enumeration<>() {
			Iterator<T> it = NSArray.this.iterator();

			@Override
			public boolean hasMoreElements() {
				return it.hasNext();
			}

			@Override
			public T nextElement() {
				return it.next();
			}
		};
	}

	/**
	 * Returns an enumeration over the elements of the array in reverse order.
	 */
	public java.util.Enumeration<T> reverseObjectEnumerator() {
		class ReverseArrayEnumerator implements Enumeration<T> {
			ListIterator<T> it = null;

			ListIterator<T> getIterator() {
				if (it == null) {
					it = NSArray.this.listIterator();
					// zoom to end
					while (it.hasNext())
						it.next();
				}
				return it;
			}

			@Override
			public boolean hasMoreElements() {
				return getIterator().hasPrevious();
			}

			@Override
			public T nextElement() {
				return getIterator().previous();
			}
		}
		return new ReverseArrayEnumerator();
	}

	/**
	 * Copies the elements of this array into the specified object array as the
	 * array's capacity permits.
	 */
	public void getObjects(T[] anArray) {
		getObjects(anArray, null);
	}

	/**
	 * Copies the elements of this array that fall within the specified range into
	 * the specified object array as the array's capacity permits. This method must
	 * not overflow, even in the face of a null range, an over or under-sized array,
	 * or a bad range. It may underflow and fail to entirely populate the array, if
	 * the array is larger than the data to be copied.
	 * 
	 * TODO: Check whether in WebObjects the range supposed to be measured against
	 * the parameter or the NSArray itself??? -ceg
	 * 
	 * @param anArray An object array to be filled by this method.
	 * @param range   An NSRange object representing the range of data in the
	 *                NSArray to be copied.
	 */
	public void getObjects(T[] array, NSRange range) {
		if (array == null)
			return;
		if (range == null)
			range = new NSRange(0, array.length);
		int limit = Math.min(Math.min(array.length, range.length()), (count() - range.location()));
		for (int i = 0; i < limit; i++) {
			// anArray[ i-aRange.location() ] = objectAtIndex( i );
			array[i] = objectAtIndex(range.location() + i);
		}
	}

	/**
	 * Returns the index of the first object in the array equivalent to the
	 * specified object. Returns NotFound if the item is not found.
	 */
	public int indexOfObject(T anObject) {
		int result = list.indexOf(anObject);
		if (result == -1)
			return NotFound; // in case this changes
		return result;
	}

	/**
	 * Returns the index of the first object in the array within the specified range
	 * equivalent to the specified object. Returns NotFound if the item is not
	 * found.
	 */
	public int indexOfObject(T anObject, NSRange aRange) {
		if ((anObject == null) || (aRange == null))
			return NotFound;

		int loc = aRange.location();
		int max = aRange.maxRange();
		for (int i = loc; i < max; i++) {
			if (anObject.equals(list.get(i))) {
				return i;
			}
		}
		return NotFound;
	}

	/**
	 * Returns the index of the specified object if it exists in the array,
	 * comparing by reference. Returns NotFound if the item is not found.
	 */
	public int indexOfIdenticalObject(T anObject) {
		int size = list.size();
		for (int i = 0; i < size; i++) {
			if (anObject == list.get(i)) {
				return i;
			}
		}
		return NotFound;
	}

	/**
	 * Returns the index of the first object in the array within the specified range
	 * equivalent to the specified object.
	 */
	public int indexOfIdenticalObject(T anObject, NSRange aRange) {
		if (aRange == null)
			return NotFound;

		int loc = aRange.location();
		int max = aRange.maxRange();
		for (int i = loc; i < max; i++) {
			if (anObject == list.get(i)) {
				return i;
			}
		}
		return NotFound;
	}

	/**
	 * Returns the object at the specified index. Throws an IndexOutOfRange
	 * exception if the index is out of range.
	 */
	public T objectAtIndex(int anIndex) {
		return list.get(anIndex);
	}

	/**
	 * Returns an array consisting of strings within the specified string as
	 * delimited by the specified separator characters.
	 */
	public static NSArray<String> componentsSeparatedByString(String aString, String aSeparator) {
		NSArray<String> result = new NSArray<>();
		if (aString == null)
			return result;
		if (aSeparator == null)
			return new NSArray<>(aString);

		// FIXME: The spec probably considers the whole
		// string as a separator, unlike string tokenizer.
		java.util.StringTokenizer tokens = new java.util.StringTokenizer(aString, aSeparator);
		while (tokens.hasMoreTokens()) {
			result.protectedAdd(tokens.nextToken());
		}

		return result;
	}

	@Override
	public Object clone() {
		return new NSArray<>(list);
	}

	public NSArray<T> immutableClone() {
		return this;
	}

	public NSMutableArray<T> mutableClone() {
		return new NSMutableArray<>(this);
	}

	@Override
	public String toString() {
		StringBuffer buf = new StringBuffer();
		buf.append(NSPropertyListSerialization.TOKEN_BEGIN[NSPropertyListSerialization.PLIST_ARRAY]);
		for (int i = 0; i < count(); i++) {
			Object x = objectAtIndex(i);
			buf.append(NSPropertyListSerialization.stringForPropertyList(x));
			if (i < count() - 1)
				buf.append(", ");
		}
		buf.append(NSPropertyListSerialization.TOKEN_END[NSPropertyListSerialization.PLIST_ARRAY]);
		return buf.toString();
	}

	// interface List: accessors

	@Override
	public boolean contains(Object o) {
		return list.contains(o);
	}

	@Override
	public boolean containsAll(Collection<?> c) {
		return list.containsAll(c);
	}

	@Override
	public boolean equals(Object o) {
		return list.equals(o);
	}

	@Override
	public T get(int index) {
		return list.get(index);
	}

	@Override
	public int hashCode() {
		int code = 19;
		code *= getClass().hashCode();
		code *= list.hashCode();
		return code;
	}

	@Override
	public int indexOf(Object o) {
		return list.indexOf(o);
	}

	@Override
	public boolean isEmpty() {
		return list.isEmpty();
	}

	@Override
	public int lastIndexOf(Object o) {
		return list.lastIndexOf(o);
	}

	@Override
	public int size() {
		return list.size();
	}

	@Override
	public Object[] toArray() {
		return list.toArray();
	}

	@SuppressWarnings("unchecked")
	@Override
	public T[] toArray(Object[] a) {
		return (T[]) list.toArray(a);
	}

	// interface List: mutators

	@Override
	public void add(int index, T element) {
		this.list.add(index, element);
	}

	@Override
	public boolean add(T o) {
		return this.list.add(o);
	}

	@Override
	public boolean addAll(Collection<? extends T> coll) {
		return this.list.addAll(coll);
	}

	@Override
	public boolean addAll(int index, Collection<? extends T> c) {
		return this.list.addAll(index, c);
	}

	@Override
	public void clear() {
		this.list.clear();
	}

	@Override
	public Iterator<T> iterator() {
		// make a copy to avoid ConcurrentModificationExceptions
		final Iterator<T> i = new LinkedList<>(list).iterator();
		return new Iterator<>() {
			@Override
			public boolean hasNext() {
				return i.hasNext();
			}

			@Override
			public T next() {
				return i.next();
			}

			@Override
			public void remove() {
				throw new UnsupportedOperationException();
			}
		};
	}

	@Override
	public ListIterator<T> listIterator() {
		return listIterator(0);
	}

	@Override
	public ListIterator<T> listIterator(final int index) {
		// make a copy to avoid ConcurrentModificationExceptions
		final ListIterator<T> i = new LinkedList<>(list).listIterator(index);
		return new ListIterator<>() {
			@Override
			public boolean hasNext() {
				return i.hasNext();
			}

			@Override
			public T next() {
				return i.next();
			}

			@Override
			public boolean hasPrevious() {
				return i.hasPrevious();
			}

			@Override
			public T previous() {
				return i.previous();
			}

			@Override
			public int nextIndex() {
				return i.nextIndex();
			}

			@Override
			public int previousIndex() {
				return i.previousIndex();
			}

			@Override
			public void remove() {
				throw new UnsupportedOperationException();
			}

			@Override
			public void set(T o) {
				throw new UnsupportedOperationException();
			}

			@Override
			public void add(T o) {
				throw new UnsupportedOperationException();
			}
		};
	}

	@Override
	public T remove(int index) {
		return this.list.remove(index);
	}

	@Override
	public boolean remove(Object o) {
		return this.list.remove(o);
	}

	@Override
	public boolean removeAll(Collection<?> coll) {
		return this.list.removeAll(coll);
	}

	@Override
	public boolean retainAll(Collection<?> coll) {
		return this.list.retainAll(coll);
	}

	@Override
	public T set(int index, T element) {
		return this.list.set(index, element);
	}

	@Override
	public List<T> subList(int fromIndex, int toIndex) {
		return Collections.unmodifiableList(list.subList(fromIndex, toIndex));
	}

	/**
	 * Provided for the use of subclasses like ArrayFault.
	 */
	protected boolean protectedAdd(T o) {
		return list.add(o);
	}

	/**
	 * Provided for the use of subclasses like ArrayFault.
	 */
	protected boolean protectedAddAll(Collection<T> coll) {
		return list.addAll(coll);
	}
}

/*
 * $Log$ Revision 1.2 2006/03/10 00:52:27 cgruber Add tests for NSArray and fix
 * some problems that became obvious as a result.
 *
 * Revision 1.1 2006/02/16 12:47:16 cgruber Check in all sources in
 * eclipse-friendly maven-enabled packages.
 *
 * Revision 1.16 2005/07/13 14:12:44 cgruber Add mutableClone() and
 * immutableClone() per. WebObjects 5.3 conformance.
 *
 * Revision 1.15 2003/08/06 23:07:52 chochos general code cleanup (mostly,
 * removing unused imports)
 *
 * Revision 1.14 2003/08/05 00:48:56 chochos use NSPropertyListSerialization to
 * get the opening and closing tokens for the string representation
 *
 * Revision 1.13 2003/08/04 20:26:10 chochos use NSPropertyListSerialization
 * inside toString()
 *
 * Revision 1.12 2003/08/04 18:18:43 chochos toString() yields strings in the
 * same format as Apple's NSArray
 *
 * Revision 1.11 2003/01/28 19:44:20 mpowers Fixed reverse enumerator.
 *
 * Revision 1.10 2003/01/18 23:49:55 mpowers Added mutableClone().
 *
 * Revision 1.9 2003/01/18 23:30:42 mpowers WODisplayGroup now compiles.
 *
 * Revision 1.8 2003/01/16 22:47:30 mpowers Compatibility changes to support
 * compiling woextensions source. (34 out of 56 classes compile!)
 *
 * Revision 1.7 2003/01/10 19:16:40 mpowers Implemented support for page
 * caching.
 *
 * Revision 1.6 2002/10/24 21:15:36 mpowers New implementations of NSArray and
 * subclasses.
 *
 * Revision 1.5 2002/10/24 18:16:30 mpowers Now enforcing NSArray's immutable
 * nature.
 *
 * Revision 1.4 2002/03/08 19:02:54 mpowers Long-overdue speed optimization of
 * indexOfIdenticalObject.
 *
 * Revision 1.3 2002/02/13 22:02:56 mpowers Fixed: bug in
 * componentsSeparatedByString when separator is null (thanks to Cedrik LIME).
 *
 * Revision 1.2 2001/01/11 20:34:26 mpowers Implemented EOSortOrdering and added
 * support in framework. Added header-click to sort table columns.
 *
 * Revision 1.1.1.1 2000/12/21 15:47:26 mpowers Contributing wotonomy.
 *
 * Revision 1.3 2000/12/20 16:25:37 michael Added log to all files.
 *
 *
 */