1/*
2 * Written by Doug Lea with assistance from members of JCP JSR-166
3 * Expert Group and released to the public domain, as explained at
4 * http://creativecommons.org/publicdomain/zero/1.0/
5 * Other contributors include Andrew Wright, Jeffrey Hayes,
6 * Pat Fisher, Mike Judd.
7 */
8
9package jsr166;
10
11import java.util.ArrayList;
12import java.util.Arrays;
13import java.util.Collection;
14import java.util.Collections;
15import java.util.Iterator;
16import java.util.LinkedList;
17import java.util.List;
18import java.util.ListIterator;
19import java.util.NoSuchElementException;
20import java.util.concurrent.CopyOnWriteArrayList;
21
22import junit.framework.Test;
23import junit.framework.TestSuite;
24
25public class CopyOnWriteArrayListTest extends JSR166TestCase {
26
27    // android-note: Removed because the CTS runner does a bad job of
28    // retrying tests that have suite() declarations.
29    //
30    // public static void main(String[] args) {
31    //     main(suite(), args);
32    // }
33    // public static Test suite() {
34    //     return new TestSuite(...);
35    // }
36
37    static CopyOnWriteArrayList<Integer> populatedArray(int n) {
38        CopyOnWriteArrayList<Integer> a = new CopyOnWriteArrayList<Integer>();
39        assertTrue(a.isEmpty());
40        for (int i = 0; i < n; i++)
41            a.add(i);
42        assertFalse(a.isEmpty());
43        assertEquals(n, a.size());
44        return a;
45    }
46
47    static CopyOnWriteArrayList<Integer> populatedArray(Integer[] elements) {
48        CopyOnWriteArrayList<Integer> a = new CopyOnWriteArrayList<Integer>();
49        assertTrue(a.isEmpty());
50        for (int i = 0; i < elements.length; i++)
51            a.add(elements[i]);
52        assertFalse(a.isEmpty());
53        assertEquals(elements.length, a.size());
54        return a;
55    }
56
57    /**
58     * a new list is empty
59     */
60    public void testConstructor() {
61        CopyOnWriteArrayList a = new CopyOnWriteArrayList();
62        assertTrue(a.isEmpty());
63    }
64
65    /**
66     * new list contains all elements of initializing array
67     */
68    public void testConstructor2() {
69        Integer[] ints = new Integer[SIZE];
70        for (int i = 0; i < SIZE-1; ++i)
71            ints[i] = new Integer(i);
72        CopyOnWriteArrayList a = new CopyOnWriteArrayList(ints);
73        for (int i = 0; i < SIZE; ++i)
74            assertEquals(ints[i], a.get(i));
75    }
76
77    /**
78     * new list contains all elements of initializing collection
79     */
80    public void testConstructor3() {
81        Integer[] ints = new Integer[SIZE];
82        for (int i = 0; i < SIZE-1; ++i)
83            ints[i] = new Integer(i);
84        CopyOnWriteArrayList a = new CopyOnWriteArrayList(Arrays.asList(ints));
85        for (int i = 0; i < SIZE; ++i)
86            assertEquals(ints[i], a.get(i));
87    }
88
89    /**
90     * addAll adds each element from the given collection, including duplicates
91     */
92    public void testAddAll() {
93        CopyOnWriteArrayList full = populatedArray(3);
94        assertTrue(full.addAll(Arrays.asList(three, four, five)));
95        assertEquals(6, full.size());
96        assertTrue(full.addAll(Arrays.asList(three, four, five)));
97        assertEquals(9, full.size());
98    }
99
100    /**
101     * addAllAbsent adds each element from the given collection that did not
102     * already exist in the List
103     */
104    public void testAddAllAbsent() {
105        CopyOnWriteArrayList full = populatedArray(3);
106        // "one" is duplicate and will not be added
107        assertEquals(2, full.addAllAbsent(Arrays.asList(three, four, one)));
108        assertEquals(5, full.size());
109        assertEquals(0, full.addAllAbsent(Arrays.asList(three, four, one)));
110        assertEquals(5, full.size());
111    }
112
113    /**
114     * addIfAbsent will not add the element if it already exists in the list
115     */
116    public void testAddIfAbsent() {
117        CopyOnWriteArrayList full = populatedArray(SIZE);
118        full.addIfAbsent(one);
119        assertEquals(SIZE, full.size());
120    }
121
122    /**
123     * addIfAbsent adds the element when it does not exist in the list
124     */
125    public void testAddIfAbsent2() {
126        CopyOnWriteArrayList full = populatedArray(SIZE);
127        full.addIfAbsent(three);
128        assertTrue(full.contains(three));
129    }
130
131    /**
132     * clear removes all elements from the list
133     */
134    public void testClear() {
135        CopyOnWriteArrayList full = populatedArray(SIZE);
136        full.clear();
137        assertEquals(0, full.size());
138    }
139
140    /**
141     * Cloned list is equal
142     */
143    public void testClone() {
144        CopyOnWriteArrayList l1 = populatedArray(SIZE);
145        CopyOnWriteArrayList l2 = (CopyOnWriteArrayList)(l1.clone());
146        assertEquals(l1, l2);
147        l1.clear();
148        assertFalse(l1.equals(l2));
149    }
150
151    /**
152     * contains is true for added elements
153     */
154    public void testContains() {
155        CopyOnWriteArrayList full = populatedArray(3);
156        assertTrue(full.contains(one));
157        assertFalse(full.contains(five));
158    }
159
160    /**
161     * adding at an index places it in the indicated index
162     */
163    public void testAddIndex() {
164        CopyOnWriteArrayList full = populatedArray(3);
165        full.add(0, m1);
166        assertEquals(4, full.size());
167        assertEquals(m1, full.get(0));
168        assertEquals(zero, full.get(1));
169
170        full.add(2, m2);
171        assertEquals(5, full.size());
172        assertEquals(m2, full.get(2));
173        assertEquals(two, full.get(4));
174    }
175
176    /**
177     * lists with same elements are equal and have same hashCode
178     */
179    public void testEquals() {
180        CopyOnWriteArrayList a = populatedArray(3);
181        CopyOnWriteArrayList b = populatedArray(3);
182        assertTrue(a.equals(b));
183        assertTrue(b.equals(a));
184        assertEquals(a.hashCode(), b.hashCode());
185        a.add(m1);
186        assertFalse(a.equals(b));
187        assertFalse(b.equals(a));
188        b.add(m1);
189        assertTrue(a.equals(b));
190        assertTrue(b.equals(a));
191        assertEquals(a.hashCode(), b.hashCode());
192    }
193
194    /**
195     * containsAll returns true for collection with subset of elements
196     */
197    public void testContainsAll() {
198        CopyOnWriteArrayList full = populatedArray(3);
199        assertTrue(full.containsAll(Arrays.asList()));
200        assertTrue(full.containsAll(Arrays.asList(one)));
201        assertTrue(full.containsAll(Arrays.asList(one, two)));
202        assertFalse(full.containsAll(Arrays.asList(one, two, six)));
203        assertFalse(full.containsAll(Arrays.asList(six)));
204    }
205
206    /**
207     * get returns the value at the given index
208     */
209    public void testGet() {
210        CopyOnWriteArrayList full = populatedArray(3);
211        assertEquals(0, full.get(0));
212    }
213
214    /**
215     * indexOf gives the index for the given object
216     */
217    public void testIndexOf() {
218        CopyOnWriteArrayList full = populatedArray(3);
219        assertEquals(1, full.indexOf(one));
220        assertEquals(-1, full.indexOf("puppies"));
221    }
222
223    /**
224     * indexOf gives the index based on the given index
225     * at which to start searching
226     */
227    public void testIndexOf2() {
228        CopyOnWriteArrayList full = populatedArray(3);
229        assertEquals(1, full.indexOf(one, 0));
230        assertEquals(-1, full.indexOf(one, 2));
231    }
232
233    /**
234     * isEmpty returns true when empty, else false
235     */
236    public void testIsEmpty() {
237        CopyOnWriteArrayList empty = new CopyOnWriteArrayList();
238        CopyOnWriteArrayList full = populatedArray(SIZE);
239        assertTrue(empty.isEmpty());
240        assertFalse(full.isEmpty());
241    }
242
243    /**
244     * iterator() returns an iterator containing the elements of the
245     * list in insertion order
246     */
247    public void testIterator() {
248        Collection empty = new CopyOnWriteArrayList();
249        assertFalse(empty.iterator().hasNext());
250        try {
251            empty.iterator().next();
252            shouldThrow();
253        } catch (NoSuchElementException success) {}
254
255        Integer[] elements = new Integer[SIZE];
256        for (int i = 0; i < SIZE; i++)
257            elements[i] = i;
258        Collections.shuffle(Arrays.asList(elements));
259        Collection<Integer> full = populatedArray(elements);
260
261        Iterator it = full.iterator();
262        for (int j = 0; j < SIZE; j++) {
263            assertTrue(it.hasNext());
264            assertEquals(elements[j], it.next());
265        }
266        assertIteratorExhausted(it);
267    }
268
269    /**
270     * iterator of empty collection has no elements
271     */
272    public void testEmptyIterator() {
273        Collection c = new CopyOnWriteArrayList();
274        assertIteratorExhausted(c.iterator());
275    }
276
277    /**
278     * iterator.remove throws UnsupportedOperationException
279     */
280    public void testIteratorRemove() {
281        CopyOnWriteArrayList full = populatedArray(SIZE);
282        Iterator it = full.iterator();
283        it.next();
284        try {
285            it.remove();
286            shouldThrow();
287        } catch (UnsupportedOperationException success) {}
288    }
289
290    /**
291     * toString contains toString of elements
292     */
293    public void testToString() {
294        assertEquals("[]", new CopyOnWriteArrayList().toString());
295        CopyOnWriteArrayList full = populatedArray(3);
296        String s = full.toString();
297        for (int i = 0; i < 3; ++i)
298            assertTrue(s.contains(String.valueOf(i)));
299        assertEquals(new ArrayList(full).toString(),
300                     full.toString());
301    }
302
303    /**
304     * lastIndexOf returns the index for the given object
305     */
306    public void testLastIndexOf1() {
307        CopyOnWriteArrayList full = populatedArray(3);
308        full.add(one);
309        full.add(three);
310        assertEquals(3, full.lastIndexOf(one));
311        assertEquals(-1, full.lastIndexOf(six));
312    }
313
314    /**
315     * lastIndexOf returns the index from the given starting point
316     */
317    public void testLastIndexOf2() {
318        CopyOnWriteArrayList full = populatedArray(3);
319        full.add(one);
320        full.add(three);
321        assertEquals(3, full.lastIndexOf(one, 4));
322        assertEquals(-1, full.lastIndexOf(three, 3));
323    }
324
325    /**
326     * listIterator traverses all elements
327     */
328    public void testListIterator1() {
329        CopyOnWriteArrayList full = populatedArray(SIZE);
330        ListIterator i = full.listIterator();
331        int j;
332        for (j = 0; i.hasNext(); j++)
333            assertEquals(j, i.next());
334        assertEquals(SIZE, j);
335    }
336
337    /**
338     * listIterator only returns those elements after the given index
339     */
340    public void testListIterator2() {
341        CopyOnWriteArrayList full = populatedArray(3);
342        ListIterator i = full.listIterator(1);
343        int j;
344        for (j = 0; i.hasNext(); j++)
345            assertEquals(j+1, i.next());
346        assertEquals(2, j);
347    }
348
349    /**
350     * remove(int) removes and returns the object at the given index
351     */
352    public void testRemove_int() {
353        int SIZE = 3;
354        for (int i = 0; i < SIZE; i++) {
355            CopyOnWriteArrayList full = populatedArray(SIZE);
356            assertEquals(i, full.remove(i));
357            assertEquals(SIZE - 1, full.size());
358            assertFalse(full.contains(new Integer(i)));
359        }
360    }
361
362    /**
363     * remove(Object) removes the object if found and returns true
364     */
365    public void testRemove_Object() {
366        int SIZE = 3;
367        for (int i = 0; i < SIZE; i++) {
368            CopyOnWriteArrayList full = populatedArray(SIZE);
369            assertFalse(full.remove(new Integer(-42)));
370            assertTrue(full.remove(new Integer(i)));
371            assertEquals(SIZE - 1, full.size());
372            assertFalse(full.contains(new Integer(i)));
373        }
374        CopyOnWriteArrayList x = new CopyOnWriteArrayList(Arrays.asList(4, 5, 6));
375        assertTrue(x.remove(new Integer(6)));
376        assertEquals(x, Arrays.asList(4, 5));
377        assertTrue(x.remove(new Integer(4)));
378        assertEquals(x, Arrays.asList(5));
379        assertTrue(x.remove(new Integer(5)));
380        assertEquals(x, Arrays.asList());
381        assertFalse(x.remove(new Integer(5)));
382    }
383
384    /**
385     * removeAll removes all elements from the given collection
386     */
387    public void testRemoveAll() {
388        CopyOnWriteArrayList full = populatedArray(3);
389        assertTrue(full.removeAll(Arrays.asList(one, two)));
390        assertEquals(1, full.size());
391        assertFalse(full.removeAll(Arrays.asList(one, two)));
392        assertEquals(1, full.size());
393    }
394
395    /**
396     * set changes the element at the given index
397     */
398    public void testSet() {
399        CopyOnWriteArrayList full = populatedArray(3);
400        assertEquals(2, full.set(2, four));
401        assertEquals(4, full.get(2));
402    }
403
404    /**
405     * size returns the number of elements
406     */
407    public void testSize() {
408        CopyOnWriteArrayList empty = new CopyOnWriteArrayList();
409        CopyOnWriteArrayList full = populatedArray(SIZE);
410        assertEquals(SIZE, full.size());
411        assertEquals(0, empty.size());
412    }
413
414    /**
415     * toArray() returns an Object array containing all elements from
416     * the list in insertion order
417     */
418    public void testToArray() {
419        Object[] a = new CopyOnWriteArrayList().toArray();
420        assertTrue(Arrays.equals(new Object[0], a));
421        assertSame(Object[].class, a.getClass());
422
423        Integer[] elements = new Integer[SIZE];
424        for (int i = 0; i < SIZE; i++)
425            elements[i] = i;
426        Collections.shuffle(Arrays.asList(elements));
427        Collection<Integer> full = populatedArray(elements);
428
429        assertTrue(Arrays.equals(elements, full.toArray()));
430        assertSame(Object[].class, full.toArray().getClass());
431    }
432
433    /**
434     * toArray(Integer array) returns an Integer array containing all
435     * elements from the list in insertion order
436     */
437    public void testToArray2() {
438        Collection empty = new CopyOnWriteArrayList();
439        Integer[] a;
440
441        a = new Integer[0];
442        assertSame(a, empty.toArray(a));
443
444        a = new Integer[SIZE/2];
445        Arrays.fill(a, 42);
446        assertSame(a, empty.toArray(a));
447        assertNull(a[0]);
448        for (int i = 1; i < a.length; i++)
449            assertEquals(42, (int) a[i]);
450
451        Integer[] elements = new Integer[SIZE];
452        for (int i = 0; i < SIZE; i++)
453            elements[i] = i;
454        Collections.shuffle(Arrays.asList(elements));
455        Collection<Integer> full = populatedArray(elements);
456
457        Arrays.fill(a, 42);
458        assertTrue(Arrays.equals(elements, full.toArray(a)));
459        for (int i = 0; i < a.length; i++)
460            assertEquals(42, (int) a[i]);
461        assertSame(Integer[].class, full.toArray(a).getClass());
462
463        a = new Integer[SIZE];
464        Arrays.fill(a, 42);
465        assertSame(a, full.toArray(a));
466        assertTrue(Arrays.equals(elements, a));
467
468        a = new Integer[2*SIZE];
469        Arrays.fill(a, 42);
470        assertSame(a, full.toArray(a));
471        assertTrue(Arrays.equals(elements, Arrays.copyOf(a, SIZE)));
472        assertNull(a[SIZE]);
473        for (int i = SIZE + 1; i < a.length; i++)
474            assertEquals(42, (int) a[i]);
475    }
476
477    /**
478     * sublists contains elements at indexes offset from their base
479     */
480    public void testSubList() {
481        CopyOnWriteArrayList a = populatedArray(10);
482        assertTrue(a.subList(1,1).isEmpty());
483        for (int j = 0; j < 9; ++j) {
484            for (int i = j ; i < 10; ++i) {
485                List b = a.subList(j,i);
486                for (int k = j; k < i; ++k) {
487                    assertEquals(new Integer(k), b.get(k-j));
488                }
489            }
490        }
491
492        List s = a.subList(2, 5);
493        assertEquals(3, s.size());
494        s.set(2, m1);
495        assertEquals(a.get(4), m1);
496        s.clear();
497        assertEquals(7, a.size());
498    }
499
500    // Exception tests
501
502    /**
503     * toArray throws an ArrayStoreException when the given array
504     * can not store the objects inside the list
505     */
506    public void testToArray_ArrayStoreException() {
507        CopyOnWriteArrayList c = new CopyOnWriteArrayList();
508        c.add("zfasdfsdf");
509        c.add("asdadasd");
510        try {
511            c.toArray(new Long[5]);
512            shouldThrow();
513        } catch (ArrayStoreException success) {}
514    }
515
516    /**
517     * get throws an IndexOutOfBoundsException on a negative index
518     */
519    public void testGet1_IndexOutOfBoundsException() {
520        CopyOnWriteArrayList c = populatedArray(5);
521        List[] lists = { c, c.subList(1, c.size() - 1) };
522        for (List list : lists) {
523            try {
524                list.get(-1);
525                shouldThrow();
526            } catch (IndexOutOfBoundsException success) {}
527        }
528    }
529
530    /**
531     * get throws an IndexOutOfBoundsException on a too high index
532     */
533    public void testGet2_IndexOutOfBoundsException() {
534        CopyOnWriteArrayList c = populatedArray(5);
535        List[] lists = { c, c.subList(1, c.size() - 1) };
536        for (List list : lists) {
537            try {
538                list.get(list.size());
539                shouldThrow();
540            } catch (IndexOutOfBoundsException success) {}
541        }
542    }
543
544    /**
545     * set throws an IndexOutOfBoundsException on a negative index
546     */
547    public void testSet1_IndexOutOfBoundsException() {
548        CopyOnWriteArrayList c = populatedArray(5);
549        List[] lists = { c, c.subList(1, c.size() - 1) };
550        for (List list : lists) {
551            try {
552                list.set(-1, "qwerty");
553                shouldThrow();
554            } catch (IndexOutOfBoundsException success) {}
555        }
556    }
557
558    /**
559     * set throws an IndexOutOfBoundsException on a too high index
560     */
561    public void testSet2() {
562        CopyOnWriteArrayList c = populatedArray(5);
563        List[] lists = { c, c.subList(1, c.size() - 1) };
564        for (List list : lists) {
565            try {
566                list.set(list.size(), "qwerty");
567                shouldThrow();
568            } catch (IndexOutOfBoundsException success) {}
569        }
570    }
571
572    /**
573     * add throws an IndexOutOfBoundsException on a negative index
574     */
575    public void testAdd1_IndexOutOfBoundsException() {
576        CopyOnWriteArrayList c = populatedArray(5);
577        List[] lists = { c, c.subList(1, c.size() - 1) };
578        for (List list : lists) {
579            try {
580                list.add(-1, "qwerty");
581                shouldThrow();
582            } catch (IndexOutOfBoundsException success) {}
583        }
584    }
585
586    /**
587     * add throws an IndexOutOfBoundsException on a too high index
588     */
589    public void testAdd2_IndexOutOfBoundsException() {
590        CopyOnWriteArrayList c = populatedArray(5);
591        List[] lists = { c, c.subList(1, c.size() - 1) };
592        for (List list : lists) {
593            try {
594                list.add(list.size() + 1, "qwerty");
595                shouldThrow();
596            } catch (IndexOutOfBoundsException success) {}
597        }
598    }
599
600    /**
601     * remove throws an IndexOutOfBoundsException on a negative index
602     */
603    public void testRemove1_IndexOutOfBounds() {
604        CopyOnWriteArrayList c = populatedArray(5);
605        List[] lists = { c, c.subList(1, c.size() - 1) };
606        for (List list : lists) {
607            try {
608                list.remove(-1);
609                shouldThrow();
610            } catch (IndexOutOfBoundsException success) {}
611        }
612    }
613
614    /**
615     * remove throws an IndexOutOfBoundsException on a too high index
616     */
617    public void testRemove2_IndexOutOfBounds() {
618        CopyOnWriteArrayList c = populatedArray(5);
619        List[] lists = { c, c.subList(1, c.size() - 1) };
620        for (List list : lists) {
621            try {
622                list.remove(list.size());
623                shouldThrow();
624            } catch (IndexOutOfBoundsException success) {}
625        }
626    }
627
628    /**
629     * addAll throws an IndexOutOfBoundsException on a negative index
630     */
631    public void testAddAll1_IndexOutOfBoundsException() {
632        CopyOnWriteArrayList c = populatedArray(5);
633        List[] lists = { c, c.subList(1, c.size() - 1) };
634        for (List list : lists) {
635            try {
636                list.addAll(-1, new LinkedList());
637                shouldThrow();
638            } catch (IndexOutOfBoundsException success) {}
639        }
640    }
641
642    /**
643     * addAll throws an IndexOutOfBoundsException on a too high index
644     */
645    public void testAddAll2_IndexOutOfBoundsException() {
646        CopyOnWriteArrayList c = populatedArray(5);
647        List[] lists = { c, c.subList(1, c.size() - 1) };
648        for (List list : lists) {
649            try {
650                list.addAll(list.size() + 1, new LinkedList());
651                shouldThrow();
652            } catch (IndexOutOfBoundsException success) {}
653        }
654    }
655
656    /**
657     * listIterator throws an IndexOutOfBoundsException on a negative index
658     */
659    public void testListIterator1_IndexOutOfBoundsException() {
660        CopyOnWriteArrayList c = populatedArray(5);
661        List[] lists = { c, c.subList(1, c.size() - 1) };
662        for (List list : lists) {
663            try {
664                list.listIterator(-1);
665                shouldThrow();
666            } catch (IndexOutOfBoundsException success) {}
667        }
668    }
669
670    /**
671     * listIterator throws an IndexOutOfBoundsException on a too high index
672     */
673    public void testListIterator2_IndexOutOfBoundsException() {
674        CopyOnWriteArrayList c = populatedArray(5);
675        List[] lists = { c, c.subList(1, c.size() - 1) };
676        for (List list : lists) {
677            try {
678                list.listIterator(list.size() + 1);
679                shouldThrow();
680            } catch (IndexOutOfBoundsException success) {}
681        }
682    }
683
684    /**
685     * subList throws an IndexOutOfBoundsException on a negative index
686     */
687    public void testSubList1_IndexOutOfBoundsException() {
688        CopyOnWriteArrayList c = populatedArray(5);
689        List[] lists = { c, c.subList(1, c.size() - 1) };
690        for (List list : lists) {
691            try {
692                list.subList(-1, list.size());
693                shouldThrow();
694            } catch (IndexOutOfBoundsException success) {}
695        }
696    }
697
698    /**
699     * subList throws an IndexOutOfBoundsException on a too high index
700     */
701    public void testSubList2_IndexOutOfBoundsException() {
702        CopyOnWriteArrayList c = populatedArray(5);
703        List[] lists = { c, c.subList(1, c.size() - 1) };
704        for (List list : lists) {
705            try {
706                list.subList(0, list.size() + 1);
707                shouldThrow();
708            } catch (IndexOutOfBoundsException success) {}
709        }
710    }
711
712    /**
713     * subList throws IndexOutOfBoundsException when the second index
714     * is lower then the first
715     */
716    public void testSubList3_IndexOutOfBoundsException() {
717        CopyOnWriteArrayList c = populatedArray(5);
718        List[] lists = { c, c.subList(1, c.size() - 1) };
719        for (List list : lists) {
720            try {
721                list.subList(list.size() - 1, 1);
722                shouldThrow();
723            } catch (IndexOutOfBoundsException success) {}
724        }
725    }
726
727    /**
728     * a deserialized serialized list is equal
729     */
730    public void testSerialization() throws Exception {
731        List x = populatedArray(SIZE);
732        List y = serialClone(x);
733
734        assertNotSame(x, y);
735        assertEquals(x.size(), y.size());
736        assertEquals(x.toString(), y.toString());
737        assertTrue(Arrays.equals(x.toArray(), y.toArray()));
738        assertEquals(x, y);
739        assertEquals(y, x);
740        while (!x.isEmpty()) {
741            assertFalse(y.isEmpty());
742            assertEquals(x.remove(0), y.remove(0));
743        }
744        assertTrue(y.isEmpty());
745    }
746
747}
748