1/*
2 *  Licensed to the Apache Software Foundation (ASF) under one or more
3 *  contributor license agreements.  See the NOTICE file distributed with
4 *  this work for additional information regarding copyright ownership.
5 *  The ASF licenses this file to You under the Apache License, Version 2.0
6 *  (the "License"); you may not use this file except in compliance with
7 *  the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *  Unless required by applicable law or agreed to in writing, software
12 *  distributed under the License is distributed on an "AS IS" BASIS,
13 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *  See the License for the specific language governing permissions and
15 *  limitations under the License.
16 */
17
18package tests.api.java.util;
19
20import dalvik.annotation.TestTargetNew;
21import dalvik.annotation.TestTargets;
22import dalvik.annotation.TestLevel;
23import dalvik.annotation.TestTargetClass;
24
25import java.util.ArrayList;
26import java.util.Collection;
27import java.util.Collections;
28import java.util.Comparator;
29import java.util.Enumeration;
30import java.util.HashMap;
31import java.util.HashSet;
32import java.util.Iterator;
33import java.util.LinkedList;
34import java.util.List;
35import java.util.ListIterator;
36import java.util.Map;
37import java.util.NoSuchElementException;
38import java.util.Random;
39import java.util.RandomAccess;
40import java.util.Set;
41import java.util.SortedSet;
42import java.util.TreeMap;
43import java.util.TreeSet;
44import java.util.Arrays;
45
46import org.apache.harmony.luni.internal.nls.Messages;
47
48import tests.support.Support_CollectionTest;
49import tests.support.Support_ListTest;
50import tests.support.Support_SetTest;
51import tests.support.Support_UnmodifiableCollectionTest;
52import tests.support.Support_UnmodifiableMapTest;
53
54@TestTargetClass(Collections.class)
55public class CollectionsTest extends junit.framework.TestCase {
56
57    private LinkedList ll;
58
59    private LinkedList myll;
60
61    private LinkedList reversedLinkedList;
62
63    private LinkedList myReversedLinkedList;
64
65    private Set s;
66
67    private Set mys;
68
69    private HashMap hm;
70
71    private Object[] objArray;
72
73    private Object[] myobjArray;
74
75    public static class ReversedMyIntComparator implements Comparator {
76        public int compare(Object o1, Object o2) {
77            return -((MyInt) o1).compareTo((MyInt) o2);
78        }
79
80        public int equals(Object o1, Object o2) {
81            return ((MyInt) o1).compareTo((MyInt) o2);
82        }
83    }
84
85    public static class SynchCollectionChecker implements Runnable {
86        Collection col;
87
88        int colSize;
89
90        int totalToRun;
91
92        boolean offset;
93
94        volatile int numberOfChecks = 0;
95
96        boolean result = true;
97
98        ArrayList normalCountingList;
99
100        ArrayList offsetCountingList;
101
102        public void run() {
103            // ensure the list either contains the numbers from 0 to size-1 or
104            // the numbers from size to 2*size -1
105            while (numberOfChecks < totalToRun) {
106                synchronized (col) {
107                    if (!(col.isEmpty() || col.containsAll(normalCountingList) || col
108                            .containsAll(offsetCountingList)))
109                        result = false;
110                    col.clear();
111                }
112                if (offset)
113                    col.addAll(offsetCountingList);
114                else
115                    col.addAll(normalCountingList);
116                numberOfChecks++;
117            }
118        }
119
120        public SynchCollectionChecker(Collection c, boolean offset,
121                int totalChecks) {
122            // The collection to test, whether to offset the filler values by
123            // size or not, and the min number of iterations to run
124            totalToRun = totalChecks;
125            col = c;
126            colSize = c.size();
127            normalCountingList = new ArrayList(colSize);
128            offsetCountingList = new ArrayList(colSize);
129            for (int counter = 0; counter < colSize; counter++)
130                normalCountingList.add(new Integer(counter));
131            for (int counter = 0; counter < colSize; counter++)
132                offsetCountingList.add(new Integer(counter + colSize));
133            col.clear();
134            if (offset)
135                col.addAll(offsetCountingList);
136            else
137                col.addAll(normalCountingList);
138        }
139
140        public boolean offset() {
141            // answer true iff the list is filled with a counting sequence
142            // starting at the value size to 2*size - 1
143            // else the list with be filled starting at 0 to size - 1
144            return offset;
145        }
146
147        public boolean getResult() {
148            // answer true iff no corruption has been found in the collection
149            return result;
150        }
151
152        public int getNumberOfChecks() {
153            // answer the number of checks that have been performed on the list
154            return numberOfChecks;
155        }
156    }
157
158    public static class SynchMapChecker implements Runnable {
159        Map map;
160
161        int mapSize;
162
163        int totalToRun;
164
165        boolean offset;
166
167        volatile int numberOfChecks = 0;
168
169        boolean result = true;
170
171        Map normalCountingMap;
172
173        Map offsetCountingMap;
174
175        public void run() {
176            Object firstNormalValue = normalCountingMap.get(new Integer(0));
177            Object lastNormalValue = normalCountingMap.get(new Integer(
178                    mapSize - 1));
179            Object firstOffsetValue = offsetCountingMap
180                    .get(new Integer(mapSize));
181            Object lastOffsetValue = offsetCountingMap.get(new Integer(
182                    2 * mapSize - 1));
183            // ensure the list either contains the numbers from 0 to size-1 or
184            // the numbers from size to 2*size -1
185            while (numberOfChecks < totalToRun) {
186                synchronized (map) {
187                    if (!(map.isEmpty()
188                            || (map.containsValue(firstNormalValue) && map
189                                    .containsValue(lastNormalValue)) || (map
190                            .containsValue(firstOffsetValue) && map
191                            .containsValue(lastOffsetValue))))
192                        result = false;
193                    map.clear();
194                }
195                if (offset)
196                    map.putAll(offsetCountingMap);
197                else
198                    map.putAll(normalCountingMap);
199                numberOfChecks++;
200            }
201        }
202
203        public SynchMapChecker(Map m, boolean offset, int totalChecks) {
204            // The collection to test, whether to offset the filler values by
205            // size or not, and the min number of iterations to run
206            Integer myInt;
207            totalToRun = totalChecks;
208            map = m;
209            mapSize = m.size();
210            normalCountingMap = new HashMap(mapSize);
211            offsetCountingMap = new HashMap(mapSize);
212            for (int counter = 0; counter < mapSize; counter++) {
213                myInt = new Integer(counter);
214                normalCountingMap.put(myInt, myInt);
215            }
216            for (int counter = 0; counter < mapSize; counter++) {
217                myInt = new Integer(counter + mapSize);
218                offsetCountingMap.put(myInt, myInt);
219            }
220            map.clear();
221            if (offset)
222                map.putAll(offsetCountingMap);
223            else
224                map.putAll(normalCountingMap);
225        }
226
227        public boolean offset() {
228            // answer true iff the list is filled with a counting sequence
229            // starting at the value size to 2*size - 1
230            // else the list with be filled starting at 0 to size - 1
231            return offset;
232        }
233
234        public boolean getResult() {
235            // answer true iff no corruption has been found in the collection
236            return result;
237        }
238
239        public int getNumberOfChecks() {
240            // answer the number of checks that have been performed on the list
241            return numberOfChecks;
242        }
243    }
244
245    public static class CollectionTest extends junit.framework.TestCase {
246
247        Collection col; // must contain the Integers 0 to 99
248
249        public CollectionTest(String p1) {
250            super(p1);
251        }
252
253        public CollectionTest(String p1, Collection c) {
254            super(p1);
255            col = c;
256        }
257
258    }
259
260    static class MyInt {
261        int data;
262
263        public MyInt(int value) {
264            data = value;
265        }
266
267        public int compareTo(MyInt object) {
268            return data > object.data ? 1 : (data < object.data ? -1 : 0);
269        }
270    }
271
272    /**
273     * @tests java.util.Collections#binarySearch(java.util.List,
274     *        java.lang.Object)
275     */
276    @TestTargetNew(
277        level = TestLevel.PARTIAL_COMPLETE,
278        notes = "Doesn't verify ClassCastException.",
279        method = "binarySearch",
280        args = {java.util.List.class, java.lang.Object.class}
281    )
282    public void test_binarySearchLjava_util_ListLjava_lang_Object() {
283        // Test for method int
284        // java.util.Collections.binarySearch(java.util.List, java.lang.Object)
285        // assumes ll is sorted and has no duplicate keys
286        final int llSize = ll.size();
287        // Ensure a NPE is thrown if the list is NULL
288        try {
289            Collections.binarySearch(null, new Object());
290            fail("Expected NullPointerException for null list parameter");
291        } catch (NullPointerException e) {
292        }
293        for (int counter = 0; counter < llSize; counter++) {
294            assertTrue("Returned incorrect binary search item position", ll
295                    .get(Collections.binarySearch(ll, ll.get(counter))) == ll
296                    .get(counter));
297        }
298    }
299
300    /**
301     * @tests java.util.Collections#binarySearch(java.util.List,
302     *        java.lang.Object, java.util.Comparator)
303     */
304    @TestTargetNew(
305        level = TestLevel.PARTIAL_COMPLETE,
306        notes = "Doesn't verify ClassCastException.",
307        method = "binarySearch",
308        args = {java.util.List.class, java.lang.Object.class, java.util.Comparator.class}
309    )
310    public void test_binarySearchLjava_util_ListLjava_lang_ObjectLjava_util_Comparator() {
311        // Test for method int
312        // java.util.Collections.binarySearch(java.util.List, java.lang.Object,
313        // java.util.Comparator)
314        // assumes reversedLinkedList is sorted in reversed order and has no
315        // duplicate keys
316        final int rSize = myReversedLinkedList.size();
317        ReversedMyIntComparator comp = new ReversedMyIntComparator();
318        // Ensure a NPE is thrown if the list is NULL
319        try {
320            Collections.binarySearch(null, new Object(), comp);
321            fail("Expected NullPointerException for null list parameter");
322        } catch (NullPointerException e) {
323        }
324        for (int counter = 0; counter < rSize; counter++) {
325            assertTrue(
326                    "Returned incorrect binary search item position using custom comparator",
327                    myReversedLinkedList.get(Collections.binarySearch(
328                            myReversedLinkedList, myReversedLinkedList
329                                    .get(counter), comp)) == myReversedLinkedList
330                            .get(counter));
331        }
332    }
333
334    class Mock_ArrayList extends ArrayList {
335        @Override
336        public
337        Object set (int index, Object o){
338            throw new UnsupportedOperationException();
339        }
340    }
341
342    /**
343     * @tests java.util.Collections#copy(java.util.List, java.util.List)
344     */
345    @TestTargetNew(
346        level = TestLevel.COMPLETE,
347        notes = "",
348        method = "copy",
349        args = {java.util.List.class, java.util.List.class}
350    )
351    public void test_copyLjava_util_ListLjava_util_List() {
352        // Test for method void java.util.Collections.copy(java.util.List,
353        // java.util.List)
354        // Ensure a NPE is thrown if the list is NULL
355        try {
356            Collections.copy(null, ll);
357            fail("Expected NullPointerException for null list first parameter");
358        } catch (NullPointerException e) {
359        }
360        try {
361            Collections.copy(ll, null);
362            fail("Expected NullPointerException for null list second parameter");
363        } catch (NullPointerException e) {
364        }
365        final int llSize = ll.size();
366        ll.set(25, null);
367        ArrayList al = new ArrayList();
368        Integer extraElement = new Integer(1);
369        Integer extraElement2 = new Integer(2);
370        al.addAll(myReversedLinkedList);
371        al.add(extraElement);
372        al.add(extraElement2);
373        Collections.copy(al, ll);
374        for (int counter = 0; counter < llSize; counter++) {
375            assertTrue("Elements do not match after copying collection", al
376                    .get(counter) == ll.get(counter));
377        }
378        assertTrue("Elements after copied elements affected by copy",
379                extraElement == al.get(llSize)
380                        && extraElement2 == al.get(llSize + 1));
381
382        ArrayList ar1 = new ArrayList();
383        ArrayList ar2 = new ArrayList();
384
385        int i;
386
387        for(i = 0; i < 5; i ++) {
388            ar2.add(new Integer(i));
389        }
390
391        for(i = 0; i < 10; i ++) {
392            ar1.add(new Integer(i));
393        }
394
395        try {
396            Collections.copy(ar2, ar1);
397            fail("IndexOutOfBoundsException expected");
398        } catch (IndexOutOfBoundsException e) {
399            //expected
400        }
401
402        Mock_ArrayList mal1 = new Mock_ArrayList();
403        Mock_ArrayList mal2 = new Mock_ArrayList();
404
405        for(i = 0; i < 10; i ++) {
406            mal1.add(new Integer(i));
407            mal2.add(new Integer(10 - i));
408        }
409
410        try {
411            Collections.copy(mal1, mal2);
412            fail("UnsupportedOperationException expected");
413        } catch (UnsupportedOperationException e) {
414            //expected
415        }
416    }
417
418    /**
419     * @tests java.util.Collections#copy(java.util.List, java.util.List)
420     */
421    @TestTargetNew(
422        level = TestLevel.PARTIAL_COMPLETE,
423        notes = "Verifies IndexOutOfBoundsException. Doesn't verify UnsupportedOperationException.",
424        method = "copy",
425        args = {java.util.List.class, java.util.List.class}
426    )
427    public void test_copy_check_index() {
428        ArrayList a1 = new ArrayList();
429        a1.add("one");
430        a1.add("two");
431
432        ArrayList a2 = new ArrayList();
433        a2.add("aa");
434
435        try {
436            Collections.copy(a2, a1);
437            fail("Expected IndexOutOfBoundsException");
438        } catch (IndexOutOfBoundsException e) {
439        }
440
441        assertEquals("aa", a2.get(0));
442    }
443
444    /**
445     * @tests java.util.Collections#enumeration(java.util.Collection)
446     */
447    @TestTargetNew(
448        level = TestLevel.COMPLETE,
449        notes = "",
450        method = "enumeration",
451        args = {java.util.Collection.class}
452    )
453    public void test_enumerationLjava_util_Collection() {
454        // Test for method java.util.Enumeration
455        // java.util.Collections.enumeration(java.util.Collection)
456        TreeSet ts = new TreeSet();
457        ts.addAll(s);
458        Enumeration e = Collections.enumeration(ts);
459        int count = 0;
460        while (e.hasMoreElements())
461            assertTrue("Returned incorrect enumeration",
462                    e.nextElement() == objArray[count++]);
463        assertTrue("Enumeration missing elements: " + count,
464                count == objArray.length);
465    }
466
467    /**
468     * @tests java.util.Collections#fill(java.util.List, java.lang.Object)
469     */
470    @TestTargetNew(
471        level = TestLevel.COMPLETE,
472        notes = "",
473        method = "fill",
474        args = {java.util.List.class, java.lang.Object.class}
475    )
476    public void test_fillLjava_util_ListLjava_lang_Object() {
477        // Test for method void java.util.Collections.fill(java.util.List,
478        // java.lang.Object)
479        try {
480            Collections.fill(null, new Object());
481            fail("Expected NullPointerException for null list parameter");
482        } catch (NullPointerException e) {
483        }
484        final int size = ll.size();
485        Collections.fill(ll, "k");
486        assertTrue("Fill modified list size", size == ll.size());
487        Iterator i = ll.iterator();
488        while (i.hasNext())
489            assertEquals("Failed to fill elements", "k", i.next());
490
491        Collections.fill(ll, null);
492        assertTrue("Fill with nulls modified list size", size == ll.size());
493        i = ll.iterator();
494        while (i.hasNext())
495            assertNull("Failed to fill with nulls", i.next());
496
497        Mock_ArrayList mal = new Mock_ArrayList();
498
499        mal.add("one");
500        mal.add("two");
501
502        try {
503            Collections.fill(mal, "value");
504            fail("UnsupportedOperationException ecpected");
505        } catch (UnsupportedOperationException e) {
506            //expected
507        }
508    }
509
510    /**
511     * @tests java.util.Collections#max(java.util.Collection)
512     */
513    @TestTargetNew(
514        level = TestLevel.COMPLETE,
515        notes = "",
516        method = "max",
517        args = {java.util.Collection.class}
518    )
519    public void test_maxLjava_util_Collection() {
520        // Test for method java.lang.Object
521        // java.util.Collections.max(java.util.Collection)
522        // assumes s, objArray are sorted
523        assertTrue("Returned incorrect max element",
524                Collections.max(s) == objArray[objArray.length - 1]);
525
526        ArrayList al = new ArrayList();
527
528        try {
529            Collections.max(al);
530            fail("NoSuchElementException expected");
531        } catch (NoSuchElementException e) {
532            //expected
533        }
534
535        al.add("String");
536        al.add(new Integer(1));
537        al.add(new Double(3.14));
538
539        try {
540            Collections.max(al);
541            fail("ClassCastException expected");
542        } catch (ClassCastException e) {
543            //expected
544        }
545    }
546
547    /**
548     * @tests java.util.Collections#max(java.util.Collection,
549     *        java.util.Comparator)
550     */
551    @TestTargetNew(
552        level = TestLevel.COMPLETE,
553        notes = "",
554        method = "max",
555        args = {java.util.Collection.class, java.util.Comparator.class}
556    )
557    public void test_maxLjava_util_CollectionLjava_util_Comparator() {
558        // Test for method java.lang.Object
559        // java.util.Collections.max(java.util.Collection, java.util.Comparator)
560        // assumes s, objArray are sorted
561
562        // With this custom (backwards) comparator the 'max' element should be
563        // the smallest in the list
564        ReversedMyIntComparator rmic = new ReversedMyIntComparator();
565        assertTrue(
566                "Returned incorrect max element using custom comparator",
567                Collections.max(mys, rmic) == myobjArray[0]);
568
569        ArrayList al = new ArrayList();
570
571        try {
572            Collections.max(al, rmic);
573            fail("NoSuchElementException expected");
574        } catch (NoSuchElementException e) {
575            //expected
576        }
577
578        al.add("String");
579        al.add(new Integer(1));
580        al.add(new Double(3.14));
581
582        try {
583            Collections.max(al, rmic);
584            fail("ClassCastException expected");
585        } catch (ClassCastException e) {
586            //expected
587        }
588    }
589
590    /**
591     * @tests java.util.Collections#min(java.util.Collection)
592     */
593    @TestTargetNew(
594        level = TestLevel.COMPLETE,
595        notes = "",
596        method = "min",
597        args = {java.util.Collection.class}
598    )
599    public void test_minLjava_util_Collection() {
600        // Test for method java.lang.Object
601        // java.util.Collections.min(java.util.Collection)
602        // assumes s, objArray are sorted
603        assertTrue("Returned incorrect min element",
604                Collections.min(s) == objArray[0]);
605        ArrayList al = new ArrayList();
606
607        try {
608            Collections.min(al);
609            fail("NoSuchElementException expected");
610        } catch (NoSuchElementException e) {
611            //expected
612        }
613
614        al.add("String");
615        al.add(new Integer(1));
616        al.add(new Double(3.14));
617
618        try {
619            Collections.min(al);
620            fail("ClassCastException expected");
621        } catch (ClassCastException e) {
622            //expected
623        }
624    }
625
626    /**
627     * @tests java.util.Collections#min(java.util.Collection,
628     *        java.util.Comparator)
629     */
630    @TestTargetNew(
631        level = TestLevel.COMPLETE,
632        notes = "",
633        method = "min",
634        args = {java.util.Collection.class, java.util.Comparator.class}
635    )
636    public void test_minLjava_util_CollectionLjava_util_Comparator() {
637        // Test for method java.lang.Object
638        // java.util.Collections.min(java.util.Collection, java.util.Comparator)
639        // assumes s, objArray are sorted
640
641        // With this custom (backwards) comparator the 'min' element should be
642        // the largest in the list
643        ReversedMyIntComparator rmic = new ReversedMyIntComparator();
644
645        assertTrue(
646                "Returned incorrect min element using custom comparator",
647                Collections.min(mys, rmic) == myobjArray[objArray.length - 1]);
648
649        ArrayList al = new ArrayList();
650
651        try {
652            Collections.min(al, rmic);
653            fail("NoSuchElementException expected");
654        } catch (NoSuchElementException e) {
655            //expected
656        }
657
658        al.add("String");
659        al.add(new Integer(1));
660        al.add(new Double(3.14));
661
662        try {
663            Collections.min(al, rmic);
664            fail("ClassCastException expected");
665        } catch (ClassCastException e) {
666            //expected
667        }
668    }
669
670    /**
671     * @tests java.util.Collections#nCopies(int, java.lang.Object)
672     */
673    @TestTargetNew(
674        level = TestLevel.COMPLETE,
675        notes = "",
676        method = "nCopies",
677        args = {int.class, java.lang.Object.class}
678    )
679    public void test_nCopiesILjava_lang_Object() {
680        // Test for method java.util.List java.util.Collections.nCopies(int,
681        // java.lang.Object)
682        Object o = new Object();
683        List l = Collections.nCopies(100, o);
684        Iterator i = l.iterator();
685        Object first = i.next();
686        assertTrue("Returned list consists of copies not refs", first == o);
687        assertEquals("Returned list of incorrect size", 100, l.size());
688        assertTrue("Contains", l.contains(o));
689        assertTrue("Contains null", !l.contains(null));
690        assertTrue("null nCopies contains", !Collections.nCopies(2, null)
691                .contains(o));
692        assertTrue("null nCopies contains null", Collections.nCopies(2, null)
693                .contains(null));
694        l = Collections.nCopies(20, null);
695        i = l.iterator();
696        for (int counter = 0; i.hasNext(); counter++) {
697            assertTrue("List is too large", counter < 20);
698            assertNull("Element should be null: " + counter, i.next());
699        }
700        try {
701            l.add(o);
702            fail("Returned list is not immutable");
703        } catch (UnsupportedOperationException e) {
704            // Correct
705            return;
706        }
707        try {
708            Collections.nCopies(-2, new HashSet());
709            fail("nCopies with negative arg didn't throw IAE");
710        } catch (IllegalArgumentException e) {
711            // Expected
712        }
713    }
714
715    /**
716     * @tests java.util.Collections#reverse(java.util.List)
717     */
718    @TestTargetNew(
719        level = TestLevel.COMPLETE,
720        notes = "",
721        method = "reverse",
722        args = {java.util.List.class}
723    )
724    public void test_reverseLjava_util_List() {
725        // Test for method void java.util.Collections.reverse(java.util.List)
726        try {
727            Collections.reverse(null);
728            fail("Expected NullPointerException for null list parameter");
729        } catch (NullPointerException e) {
730        }
731        Collections.reverse(ll);
732        Iterator i = ll.iterator();
733        int count = objArray.length - 1;
734        while (i.hasNext()) {
735            assertTrue("Failed to reverse collection",
736                    i.next() == objArray[count]);
737            --count;
738        }
739        ArrayList myList = new ArrayList();
740        myList.add(null);
741        myList.add(new Integer(20));
742        Collections.reverse(myList);
743        assertTrue("Did not reverse correctly--first element is: "
744                + myList.get(0), myList.get(0).equals(new Integer(20)));
745        assertNull("Did not reverse correctly--second element is: "
746                + myList.get(1), myList.get(1));
747
748        Mock_ArrayList mal = new Mock_ArrayList();
749
750        mal.add("First");
751        mal.add("Second");
752
753        try {
754            Collections.reverse(mal);
755            fail("UnsupportedOperationException expected");
756        } catch (UnsupportedOperationException e) {
757            //expected
758        }
759    }
760
761    /**
762     * @tests java.util.Collections#reverseOrder()
763     */
764    @TestTargetNew(
765        level = TestLevel.COMPLETE,
766        notes = "",
767        method = "reverseOrder",
768        args = {}
769    )
770    public void test_reverseOrder() {
771        // Test for method java.util.Comparator
772        // java.util.Collections.reverseOrder()
773        // assumes no duplicates in ll
774        Comparator comp = Collections.reverseOrder();
775        LinkedList list2 = new LinkedList(ll);
776        Collections.sort(list2, comp);
777        final int llSize = ll.size();
778        for (int counter = 0; counter < llSize; counter++)
779            assertTrue("New comparator does not reverse sorting order", ll
780                    .get(counter) == list2.get(llSize - counter - 1));
781    }
782
783    /**
784     * @tests java.util.Collections#shuffle(java.util.List)
785     */
786    @TestTargetNew(
787        level = TestLevel.COMPLETE,
788        notes = "",
789        method = "shuffle",
790        args = {java.util.List.class}
791    )
792    public void test_shuffleLjava_util_List() {
793        // Test for method void java.util.Collections.shuffle(java.util.List)
794        // Assumes ll is sorted and has no duplicate keys and is large ( > 20
795        // elements)
796
797        // test shuffling a Sequential Access List
798        try {
799            Collections.shuffle(null);
800            fail("Expected NullPointerException for null list parameter");
801        } catch (NullPointerException e) {
802        }
803        ArrayList al = new ArrayList();
804        al.addAll(ll);
805        testShuffle(al, "Sequential Access", false);
806
807        // test shuffling a Random Access List
808        LinkedList ll2 = new LinkedList();
809        ll2.addAll(ll);
810        testShuffle(ll2, "Random Access", false);
811    }
812
813    public void testShuffleRandomAccessWithSeededRandom() {
814        List<String> list = Arrays.asList("A", "B", "C", "D", "E", "F", "G");
815        Collections.shuffle(list, new Random(0));
816        assertEquals(Arrays.asList("B", "A", "D", "C", "G", "E", "F"), list);
817    }
818
819    public void testShuffleWithSeededRandom() {
820        List<String> list = new LinkedList<String>(Arrays.asList(
821                "A", "B", "C", "D", "E", "F", "G"));
822        Collections.shuffle(list, new Random(0));
823        assertEquals(Arrays.asList("B", "A", "D", "C", "G", "E", "F"), list);
824    }
825
826    private void testShuffle(List list, String type, boolean random) {
827        boolean sorted = true;
828        boolean allMatch = true;
829        int index = 0;
830        final int size = list.size();
831
832        if (random)
833            Collections.shuffle(list);
834        else
835            Collections.shuffle(list, new Random(200));
836
837        for (int counter = 0; counter < size - 1; counter++) {
838            if (((Integer) list.get(counter)).compareTo((Integer)list.get(counter + 1)) > 0) {
839                sorted = false;
840            }
841        }
842        assertFalse("Shuffling sorted " + type
843                + " list resulted in sorted list (should be unlikely)", sorted);
844        for (int counter = 0; counter < 20; counter++) {
845            index = 30031 * counter % (size + 1); // 30031 is a large prime
846            if (list.get(index) != ll.get(index))
847                allMatch = false;
848        }
849        assertFalse("Too many element positions match in shuffled " + type
850                + " list", allMatch);
851    }
852
853    /**
854     * @tests java.util.Collections#shuffle(java.util.List, java.util.Random)
855     */
856    @TestTargetNew(
857        level = TestLevel.COMPLETE,
858        notes = "",
859        method = "shuffle",
860        args = {java.util.List.class, java.util.Random.class}
861    )
862    public void test_shuffleLjava_util_ListLjava_util_Random() {
863        // Test for method void java.util.Collections.shuffle(java.util.List,
864        // java.util.Random)
865        // Assumes ll is sorted and has no duplicate keys and is large ( > 20
866        // elements)
867
868        // test shuffling a Sequential Access List
869        try {
870            Collections.shuffle(null, new Random(200));
871            fail("Expected NullPointerException for null list parameter");
872        } catch (NullPointerException e) {
873        }
874        ArrayList al = new ArrayList();
875        al.addAll(ll);
876        testShuffle(al, "Sequential Access", true);
877
878        // test shuffling a Random Access List
879        LinkedList ll2 = new LinkedList();
880        ll2.addAll(ll);
881        testShuffle(ll2, "Random Access", true);
882
883
884        Mock_ArrayList mal = new Mock_ArrayList();
885
886        mal.add("First");
887        mal.add("Second");
888
889        try {
890            Collections.shuffle(mal, new Random(200));
891            fail("UnsupportedOperationException expected");
892        } catch (UnsupportedOperationException e) {
893            //expected
894        }
895}
896
897    /**
898     * @tests java.util.Collections#singleton(java.lang.Object)
899     */
900    @TestTargetNew(
901        level = TestLevel.COMPLETE,
902        notes = "",
903        method = "singleton",
904        args = {java.lang.Object.class}
905    )
906    public void test_singletonLjava_lang_Object() {
907        // Test for method java.util.Set
908        // java.util.Collections.singleton(java.lang.Object)
909        Object o = new Object();
910        Set single = Collections.singleton(o);
911        assertEquals("Wrong size", 1, single.size());
912        assertTrue("Contains", single.contains(o));
913        assertTrue("Contains null", !single.contains(null));
914        assertTrue("null nCopies contains", !Collections.singleton(null)
915                .contains(o));
916        assertTrue("null nCopies contains null", Collections.singleton(null)
917                .contains(null));
918        try {
919            single.add("l");
920        } catch (UnsupportedOperationException e) {
921            // Correct
922            return;
923        }
924        fail("Allowed modification of singleton");
925    }
926
927    /**
928     * @tests java.util.Collections#sort(java.util.List)
929     */
930    @TestTargetNew(
931        level = TestLevel.COMPLETE,
932        notes = "",
933        method = "sort",
934        args = {java.util.List.class}
935    )
936    public void test_sortLjava_util_List() {
937        // Test for method void java.util.Collections.sort(java.util.List)
938        // assumes no duplicate keys in ll
939        final int llSize = ll.size();
940        final int rllSize = reversedLinkedList.size();
941        try {
942                        Collections.sort((List)null);
943            fail("Expected NullPointerException for null list parameter");
944        } catch (NullPointerException e) {
945        }
946        Collections.shuffle(ll);
947        Collections.sort(ll);
948        Collections.sort(reversedLinkedList);
949        for (int counter = 0; counter < llSize - 1; counter++) {
950            assertTrue(
951                    "Sorting shuffled list resulted in unsorted list",
952                    ((Integer) ll.get(counter)).compareTo((Integer)ll.get(counter + 1)) < 0);
953        }
954
955        for (int counter = 0; counter < rllSize - 1; counter++) {
956            assertTrue("Sorting reversed list resulted in unsorted list",
957                    ((Integer) reversedLinkedList.get(counter))
958                            .compareTo((Integer)reversedLinkedList.get(counter + 1)) < 0);
959        }
960
961        ArrayList al = new ArrayList();
962
963        al.add("String");
964        al.add(new Integer(1));
965        al.add(new Double(3.14));
966
967        try {
968            Collections.sort(al);
969            fail("ClassCastException expected");
970        } catch (ClassCastException e) {
971            //expected
972        }
973
974        Mock_ArrayList mal = new Mock_ArrayList();
975
976        mal.add("First");
977        mal.add("Second");
978
979        try {
980            Collections.sort(mal);
981            fail("UnsupportedOperationException expected");
982        } catch (UnsupportedOperationException e) {
983            //expected
984        }
985   }
986
987    /**
988     * @tests java.util.Collections#sort(java.util.List, java.util.Comparator)
989     */
990    @TestTargetNew(
991        level = TestLevel.COMPLETE,
992        notes = "",
993        method = "sort",
994        args = {java.util.List.class, java.util.Comparator.class}
995    )
996    public void test_sortLjava_util_ListLjava_util_Comparator() {
997        // Test for method void java.util.Collections.sort(java.util.List,
998        // java.util.Comparator)
999        Comparator comp = new ReversedMyIntComparator();
1000        try {
1001            Collections.sort(null, comp);
1002            fail("Expected NullPointerException for null list parameter");
1003        } catch (NullPointerException e) {
1004        }
1005        Collections.shuffle(myll);
1006        Collections.sort(myll, comp);
1007        final int llSize = myll.size();
1008
1009        for (int counter = 0; counter < llSize - 1; counter++) {
1010            assertTrue(
1011                    "Sorting shuffled list with custom comparator resulted in unsorted list",
1012                    ((MyInt) myll.get(counter)).compareTo((MyInt) myll
1013                            .get(counter + 1)) >= 0);
1014        }
1015
1016        ArrayList al = new ArrayList();
1017
1018        al.add("String");
1019        al.add(new Integer(1));
1020        al.add(new Double(3.14));
1021
1022        try {
1023            Collections.sort(al, comp);
1024            fail("ClassCastException expected");
1025        } catch (ClassCastException e) {
1026            //expected
1027        }
1028
1029        Mock_ArrayList mal = new Mock_ArrayList();
1030
1031        mal.add(new MyInt(1));
1032        mal.add(new MyInt(2));
1033
1034        try {
1035            Collections.sort(mal, comp);
1036            fail("UnsupportedOperationException expected");
1037        } catch (UnsupportedOperationException e) {
1038            //expected
1039        }
1040    }
1041
1042    /**
1043     * @tests java.util.Collections#swap(java.util.List, int, int)
1044     */
1045    @TestTargetNew(
1046        level = TestLevel.COMPLETE,
1047        notes = "",
1048        method = "swap",
1049        args = {java.util.List.class, int.class, int.class}
1050    )
1051    public void test_swapLjava_util_ListII() {
1052        // Test for method swap(java.util.List, int, int)
1053
1054        LinkedList smallList = new LinkedList();
1055        for (int i = 0; i < 10; i++) {
1056            smallList.add(objArray[i]);
1057        }
1058
1059        // test exception cases
1060        try {
1061            Collections.swap(smallList, -1, 6);
1062            fail("Expected IndexOutOfBoundsException for -1");
1063        } catch (IndexOutOfBoundsException e) {
1064        }
1065
1066        try {
1067            Collections.swap(smallList, 6, -1);
1068            fail("Expected IndexOutOfBoundsException for -1");
1069        } catch (IndexOutOfBoundsException e) {
1070        }
1071
1072        try {
1073            Collections.swap(smallList, 6, 11);
1074            fail("Expected IndexOutOfBoundsException for 11");
1075        } catch (IndexOutOfBoundsException e) {
1076        }
1077
1078        try {
1079            Collections.swap(smallList, 11, 6);
1080            fail("Expected IndexOutOfBoundsException for 11");
1081        } catch (IndexOutOfBoundsException e) {
1082        }
1083
1084        // Ensure a NPE is thrown if the list is NULL
1085        try {
1086            Collections.swap(null, 1, 1);
1087            fail("Expected NullPointerException for null list parameter");
1088        } catch (NullPointerException e) {
1089        }
1090
1091        // test with valid parameters
1092        Collections.swap(smallList, 4, 7);
1093        assertEquals("Didn't Swap the element at position 4 ", new Integer(7),
1094                smallList.get(4));
1095        assertEquals("Didn't Swap the element at position 7 ", new Integer(4),
1096                smallList.get(7));
1097
1098        // make sure other elements didn't get swapped by mistake
1099        for (int i = 0; i < 10; i++) {
1100            if (i != 4 && i != 7)
1101                assertEquals("shouldn't have swapped the element at position "
1102                        + i, new Integer(i), smallList.get(i));
1103        }
1104    }
1105
1106    /**
1107     * @tests java.util.Collections#replaceAll(java.util.List, java.lang.Object,
1108     *        java.lang.Object)
1109     */
1110    @TestTargetNew(
1111        level = TestLevel.COMPLETE,
1112        notes = "",
1113        method = "replaceAll",
1114        args = {java.util.List.class, java.lang.Object.class, java.lang.Object.class}
1115    )
1116    public void test_replaceAllLjava_util_ListLjava_lang_ObjectLjava_lang_Object() {
1117        // Test for method replaceAll(java.util.List, java.lang.Object,
1118        // java.lang.Object)
1119
1120        String string1 = "A-B-C-D-E-S-JF-SUB-G-H-I-J-SUBL-K-L-LIST-M-N--S-S-O-SUBLIS-P-Q-R-SUBLIST-S-T-U-V-W-X-Y-Z";
1121        char[] chars = string1.toCharArray();
1122        List list = new ArrayList();
1123        for (int i = 0; i < chars.length; i++) {
1124            list.add(new Character(chars[i]));
1125        }
1126
1127        try {
1128            Collections.replaceAll(null, new Object(), new Object());
1129            fail("Expected NullPointerException for null list parameter");
1130        } catch (NullPointerException e) {
1131        }
1132
1133        // test replace for an element that is not in the list
1134        boolean result = Collections.replaceAll(list, new Character('1'),
1135                new Character('Z'));
1136        assertFalse("Test1: Collections.replaceAll() returned wrong result",
1137                result);
1138        assertEquals("Test2 : ReplaceAll modified the list incorrectly",
1139                string1, getString(list));
1140
1141        // test replace for an element that is in the list
1142        result = Collections.replaceAll(list, new Character('S'),
1143                new Character('K'));
1144        assertTrue("Test3: Collections.replaceAll() returned wrong result",
1145                result);
1146        assertEquals("Test4: ReplaceAll modified the list incorrectly",
1147                (string1 = string1.replace('S', 'K')), getString(list));
1148
1149        // test replace for the last element in the list
1150        result = Collections.replaceAll(list, new Character('Z'),
1151                new Character('N'));
1152        assertTrue("Test5: Collections.replaceAll() returned wrong result",
1153                result);
1154        assertEquals("Test6: ReplaceAll modified the list incorrectly",
1155                (string1 = string1.replace('Z', 'N')), getString(list));
1156
1157        // test replace for the first element in the list
1158        result = Collections.replaceAll(list, new Character('A'),
1159                new Character('B'));
1160        assertTrue("Test7: Collections.replaceAll() returned wrong result",
1161                result);
1162        assertEquals("Test8: ReplaceAll modified the list incorrectly",
1163                (string1 = string1.replace('A', 'B')), getString(list));
1164
1165        // test replacing elements with null
1166        LinkedList smallList = new LinkedList();
1167        for (int i = 0; i < 10; i++) {
1168            smallList.add(objArray[i]);
1169        }
1170        smallList.set(4, new Integer(5));
1171        result = Collections.replaceAll(smallList, new Integer(5), null);
1172        assertTrue("Test9: Collections.replaceAll() returned wrong result",
1173                result);
1174        for (int i = 0; i < smallList.size(); i++) {
1175            if (i == 4 || i == 5)
1176                assertSame("Test9: ReplaceAll didn't replace element at " + i,
1177                        null, smallList.get(i));
1178            else
1179                assertEquals(
1180                        "Test9: ReplaceAll shouldn't have replaced element at "
1181                                + i, new Integer(i), smallList.get(i));
1182        }
1183
1184        // test replacing null elements with another value
1185        result = Collections.replaceAll(smallList, null, new Integer(99));
1186        assertTrue("Test10: Collections.replaceAll() returned wrong result",
1187                result);
1188
1189        for (int i = 0; i < smallList.size(); i++) {
1190            if (i == 4 || i == 5)
1191                assertEquals("Test10: ReplaceAll didn't replace element at "
1192                        + i, new Integer(99), smallList.get(i));
1193            else
1194                assertEquals(
1195                        "Test10: ReplaceAll shouldn't have replaced element at "
1196                                + i, new Integer(i), smallList.get(i));
1197        }
1198
1199        Mock_ArrayList mal = new Mock_ArrayList();
1200
1201        mal.add("First");
1202        mal.add("Second");
1203
1204        try {
1205            Collections.replaceAll(mal, "Second", null);
1206            fail("UnsupportedOperationException expected");
1207        } catch (UnsupportedOperationException e) {
1208            //expected
1209        }
1210    }
1211
1212    /**
1213     * @tests java.util.Collections#rotate(java.util.List, int)
1214     */
1215    @TestTargetNew(
1216        level = TestLevel.PARTIAL_COMPLETE,
1217        notes = "Verifies functionality, and UnsupportedOperationException.",
1218        method = "rotate",
1219        args = {java.util.List.class, int.class}
1220    )
1221    public void test_rotateLjava_util_ListI() {
1222        // Test for method rotate(java.util.List, int)
1223
1224        try {
1225            Collections.rotate(null, 0);
1226            fail("Expected NullPointerException for null list parameter");
1227        } catch (NullPointerException e) {
1228        }
1229
1230        // Test rotating a Sequential Access List
1231        LinkedList list1 = new LinkedList();
1232        for (int i = 0; i < 10; i++) {
1233            list1.add(objArray[i]);
1234        }
1235        testRotate(list1, "Sequential Access");
1236
1237        // Test rotating a Random Access List
1238        ArrayList list2 = new ArrayList();
1239        for (int i = 0; i < 10; i++) {
1240            list2.add(objArray[i]);
1241        }
1242        testRotate(list2, "Random Access");
1243    }
1244
1245    private void testRotate(List list, String type) {
1246        // rotate with positive distance
1247        Collections.rotate(list, 7);
1248        assertEquals("Test1: rotate modified the " + type
1249                + " list incorrectly,", "3456789012", getString(list));
1250
1251        // rotate with negative distance
1252        Collections.rotate(list, -2);
1253        assertEquals("Test2: rotate modified the " + type
1254                + " list incorrectly,", "5678901234", getString(list));
1255
1256        // rotate sublist with negative distance
1257        List subList = list.subList(1, 5);
1258        Collections.rotate(subList, -1);
1259        assertEquals("Test3: rotate modified the " + type
1260                + " list incorrectly,", "5789601234", getString(list));
1261
1262        // rotate sublist with positive distance
1263        Collections.rotate(subList, 2);
1264        assertEquals("Test4: rotate modified the " + type
1265                + " list incorrectly,", "5967801234", getString(list));
1266
1267        // rotate with positive distance that is larger than list size
1268        Collections.rotate(list, 23);
1269        assertEquals("Test5: rotate modified the " + type
1270                + " list incorrectly,", "2345967801", getString(list));
1271
1272        // rotate with negative distance that is larger than list size
1273        Collections.rotate(list, -23);
1274        assertEquals("Test6: rotate modified the " + type
1275                + " list incorrectly,", "5967801234", getString(list));
1276
1277        // rotate with 0 and equivalent distances, this should make no
1278        // modifications to the list
1279        Collections.rotate(list, 0);
1280        assertEquals("Test7: rotate modified the " + type
1281                + " list incorrectly,", "5967801234", getString(list));
1282
1283        Collections.rotate(list, -30);
1284        assertEquals("Test8: rotate modified the " + type
1285                + " list incorrectly,", "5967801234", getString(list));
1286
1287        Collections.rotate(list, 30);
1288        assertEquals("Test9: rotate modified the " + type
1289                + " list incorrectly,", "5967801234", getString(list));
1290    }
1291
1292    private String getString(List list) {
1293        StringBuffer buffer = new StringBuffer();
1294        for (int i = 0; i < list.size(); i++) {
1295            buffer.append(list.get(i));
1296        }
1297        return buffer.toString();
1298    }
1299
1300    /**
1301     * @tests java.util.Collections#rotate(java.util.List, int)
1302     */
1303    @TestTargetNew(
1304        level = TestLevel.COMPLETE,
1305        notes = "",
1306        method = "rotate",
1307        args = {java.util.List.class, int.class}
1308    )
1309    public void test_rotate2() {
1310        List list = new ArrayList();
1311        try {
1312            Collections.rotate(list, 5);
1313        } catch (UnsupportedOperationException e) {
1314            fail("Unexpected UnsupportedOperationException for empty list, "
1315                    + e);
1316        }
1317
1318        list.add(0, "zero");
1319        list.add(1, "one");
1320        list.add(2, "two");
1321        list.add(3, "three");
1322        list.add(4, "four");
1323
1324        Collections.rotate(list, Integer.MIN_VALUE);
1325        assertEquals("Rotated incorrectly at position 0, ", "three",
1326                (String) list.get(0));
1327        assertEquals("Rotated incorrectly at position 1, ", "four",
1328                (String) list.get(1));
1329        assertEquals("Rotated incorrectly at position 2, ", "zero",
1330                (String) list.get(2));
1331        assertEquals("Rotated incorrectly at position 3, ", "one",
1332                (String) list.get(3));
1333        assertEquals("Rotated incorrectly at position 4, ", "two",
1334                (String) list.get(4));
1335    }
1336
1337    /**
1338     * @tests java.util.Collections#indexOfSubList(java.util.List,
1339     *        java.util.List)
1340     */
1341    @TestTargetNew(
1342        level = TestLevel.PARTIAL_COMPLETE,
1343        notes = "Verifies boundary conditions, and NullPointerException.",
1344        method = "indexOfSubList",
1345        args = {java.util.List.class, java.util.List.class}
1346    )
1347    public void test_indexOfSubListLjava_util_ListLjava_util_List() {
1348        // Test for method int indexOfSubList(java.util.List, java.util.List)
1349        List list = new ArrayList();
1350        try {
1351            Collections.indexOfSubList(null, list);
1352            fail("Expected NullPointerException for null list first parameter");
1353        } catch (NullPointerException e) {
1354        }
1355        try {
1356            Collections.indexOfSubList(list, null);
1357            fail("Expected NullPointerException for null list second parameter");
1358        } catch (NullPointerException e) {
1359        }
1360
1361        String string1 = "A-B-C-D-E-S-JF-SUB-G-H-I-J-SUBL-K-L-LIST-M-N--S-S-O-SUBLIS-P-Q-R-SUBLIST-S-T-U-V-W-X-Y-Z";
1362
1363        testwithCharList(1, string1, "B", true);
1364        testwithCharList(2, string1, "LIST", true);
1365        testwithCharList(3, string1, "SUBLIST", true);
1366        testwithCharList(4, string1, "NONE", true);
1367        testwithCharList(5, string1, "END", true);
1368
1369        // test boundary conditions:
1370        testwithCharList(6, "", "", true);
1371        testwithCharList(7, "LIST", "", true);
1372        testwithCharList(8, "", "SUBLIST", true);
1373    }
1374
1375    /**
1376     * @tests java.util.Collections#indexOfSubList(java.util.List,
1377     *        java.util.List)
1378     */
1379    @TestTargetNew(
1380        level = TestLevel.COMPLETE,
1381        notes = "",
1382        method = "indexOfSubList",
1383        args = {java.util.List.class, java.util.List.class}
1384    )
1385    public void test_indexOfSubList2() {
1386        ArrayList sub = new ArrayList();
1387        sub.add(new Integer(1));
1388        sub.add(new Integer(2));
1389        sub.add(new Integer(3));
1390
1391        ArrayList sub2 = new ArrayList();
1392        sub2.add(new Integer(7));
1393        sub2.add(new Integer(8));
1394
1395        ArrayList src = new ArrayList();
1396        src.addAll(sub);
1397        src.addAll(sub);
1398        src.addAll(sub);
1399        src.add(new Integer(5));
1400        src.add(new Integer(6));
1401
1402        // so src becomes a list like this:
1403        // [1, 2, 3, 1, 2, 3, 1, 2, 3, 5, 6]
1404
1405        sub = new ArrayList(src.subList(3, 11));
1406        // [1, 2, 3, 1, 2, 3, 5, 6]
1407        assertEquals("TestA : Returned wrong indexOfSubList, ", 3, Collections
1408                .indexOfSubList(src, sub));
1409
1410        sub = new ArrayList(src.subList(6, 11));
1411        // [1, 2, 3, 5, 6]
1412        assertEquals("TestB : Returned wrong indexOfSubList, ", 6, Collections
1413                .indexOfSubList(src, sub));
1414
1415        sub = new ArrayList(src.subList(0, 3));
1416        // [1, 2, 3]
1417        assertEquals("TestCC : Returned wrong indexOfSubList, ", 0, Collections
1418                .indexOfSubList(src, sub));
1419
1420        sub = new ArrayList(src.subList(9, 11));
1421        // [5, 6]
1422        assertEquals("TestD : Returned wrong indexOfSubList, ", 9, Collections
1423                .indexOfSubList(src, sub));
1424
1425        sub = new ArrayList(src.subList(10, 11));
1426        // [6]
1427        assertEquals("TestE : Returned wrong indexOfSubList, ", 10, Collections
1428                .indexOfSubList(src, sub));
1429
1430        sub = new ArrayList(src.subList(0, 11));
1431        // the whole list
1432        assertEquals("TestH : Returned wrong indexIndexOfSubList, ", 0,
1433                Collections.indexOfSubList(src, sub));
1434
1435        // a non-matching list
1436        assertEquals("TestI : Returned wrong indexOfSubList, ", -1, Collections
1437                .indexOfSubList(src, sub2));
1438    }
1439
1440
1441    private void testwithCharList(int count, String string1, String string2,
1442            boolean first) {
1443        char[] chars = string1.toCharArray();
1444        List list = new ArrayList();
1445        for (int i = 0; i < chars.length; i++) {
1446            list.add(new Character(chars[i]));
1447        }
1448        chars = string2.toCharArray();
1449        List sublist = new ArrayList();
1450        for (int i = 0; i < chars.length; i++) {
1451            sublist.add(new Character(chars[i]));
1452        }
1453
1454        if (first)
1455            assertEquals("Test " + count + ": Returned wrong index:", string1
1456                    .indexOf(string2), Collections
1457                    .indexOfSubList(list, sublist));
1458        else
1459            assertEquals("Test " + count + ": Returned wrong index:", string1
1460                    .lastIndexOf(string2), Collections.lastIndexOfSubList(list,
1461                    sublist));
1462    }
1463
1464    /**
1465     * @tests java.util.Collections#lastIndexOfSubList(java.util.List,
1466     *        java.util.List)
1467     */
1468    @TestTargetNew(
1469        level = TestLevel.PARTIAL_COMPLETE,
1470        notes = "Verifies NullPointerException, and boundary conditions.",
1471        method = "lastIndexOfSubList",
1472        args = {java.util.List.class, java.util.List.class}
1473    )
1474    public void test_lastIndexOfSubListLjava_util_ListLjava_util_List() {
1475        // Test for method int lastIndexOfSubList(java.util.List,
1476        // java.util.List)
1477        String string1 = "A-B-C-D-E-S-JF-SUB-G-H-I-J-SUBL-K-L-LIST-M-N--S-S-O-SUBLIS-P-Q-R-SUBLIST-S-T-U-V-W-X-Y-Z-END";
1478
1479        List list = new ArrayList();
1480        try {
1481            Collections.lastIndexOfSubList(null, list);
1482            fail("Expected NullPointerException for null list first parameter");
1483        } catch (NullPointerException e) {
1484        }
1485        try {
1486            Collections.lastIndexOfSubList(list, null);
1487            fail("Expected NullPointerException for null list second parameter");
1488        } catch (NullPointerException e) {
1489        }
1490
1491        testwithCharList(1, string1, "B", false);
1492        testwithCharList(2, string1, "LIST", false);
1493        testwithCharList(3, string1, "SUBLIST", false);
1494        testwithCharList(4, string1, "END", false);
1495        testwithCharList(5, string1, "NONE", false);
1496
1497        // test boundary conditions
1498        testwithCharList(6, "", "", false);
1499        testwithCharList(7, "LIST", "", false);
1500        testwithCharList(8, "", "SUBLIST", false);
1501    }
1502
1503    /**
1504     * @tests java.util.Collections#lastIndexOfSubList(java.util.List,
1505     *        java.util.List)
1506     */
1507    @TestTargetNew(
1508        level = TestLevel.COMPLETE,
1509        notes = "",
1510        method = "lastIndexOfSubList",
1511        args = {java.util.List.class, java.util.List.class}
1512    )
1513    public void test_lastIndexOfSubList2() {
1514        ArrayList sub = new ArrayList();
1515        sub.add(new Integer(1));
1516        sub.add(new Integer(2));
1517        sub.add(new Integer(3));
1518
1519        ArrayList sub2 = new ArrayList();
1520        sub2.add(new Integer(7));
1521        sub2.add(new Integer(8));
1522
1523        ArrayList src = new ArrayList();
1524        src.addAll(sub);
1525        src.addAll(sub);
1526        src.addAll(sub);
1527        src.add(new Integer(5));
1528        src.add(new Integer(6));
1529
1530        // so src is a list like this:
1531        // [1, 2, 3, 1, 2, 3, 1, 2, 3, 5, 6]
1532
1533        Collections.reverse(src);
1534        // it becomes like this :
1535        // [6, 5, 3, 2, 1, 3, 2, 1, 3, 2, 1]
1536
1537        sub = new ArrayList(src.subList(0, 8));
1538        // [6, 5, 3, 2, 1, 3, 2, 1]
1539        assertEquals("TestA : Returned wrong lastIndexOfSubList, ", 0,
1540                Collections.lastIndexOfSubList(src, sub));
1541
1542        sub = new ArrayList(src.subList(0, 5));
1543        // [6, 5, 3, 2, 1]
1544        assertEquals("TestB : Returned wrong lastIndexOfSubList, ", 0,
1545                Collections.lastIndexOfSubList(src, sub));
1546
1547        sub = new ArrayList(src.subList(2, 5));
1548        // [3, 2, 1]
1549        assertEquals("TestC : Returned wrong lastIndexOfSubList, ", 8,
1550                Collections.lastIndexOfSubList(src, sub));
1551
1552        sub = new ArrayList(src.subList(9, 11));
1553        // [2, 1]
1554        assertEquals("TestD : Returned wrong lastIndexOfSubList, ", 9,
1555                Collections.lastIndexOfSubList(src, sub));
1556
1557        sub = new ArrayList(src.subList(10, 11));
1558        // [1]
1559        assertEquals("TestE : Returned wrong lastIndexOfSubList, ", 10,
1560                Collections.lastIndexOfSubList(src, sub));
1561
1562        sub = new ArrayList(src.subList(0, 2));
1563        // [6, 5]
1564        assertEquals("TestF : Returned wrong lastIndexOfSubList, ", 0,
1565                Collections.lastIndexOfSubList(src, sub));
1566
1567        sub = new ArrayList(src.subList(0, 1));
1568        // [6]
1569        assertEquals("TestG : Returned wrong lastIndexOfSubList, ", 0,
1570                Collections.lastIndexOfSubList(src, sub));
1571
1572        sub = new ArrayList(src.subList(0, 11));
1573        // the whole list
1574        assertEquals("TestH : Returned wrong lastIndexOfSubList, ", 0,
1575                Collections.lastIndexOfSubList(src, sub));
1576
1577        // a non-matching list
1578        assertEquals("TestI : Returned wrong lastIndexOfSubList, ", -1,
1579                Collections.lastIndexOfSubList(src, sub2));
1580    }
1581
1582    /**
1583     * @tests java.util.Collections#list(java.util.Enumeration)
1584     */
1585    @TestTargetNew(
1586        level = TestLevel.COMPLETE,
1587        notes = "",
1588        method = "list",
1589        args = {java.util.Enumeration.class}
1590    )
1591    public void test_listLjava_util_Enumeration() {
1592        // Test for method java.util.ArrayList list(java.util.Enumeration)
1593
1594        Enumeration e = Collections.enumeration(ll);
1595        ArrayList al = Collections.list(e);
1596
1597        int size = al.size();
1598        assertEquals("Wrong size", ll.size(), size);
1599
1600        for (int i = 0; i < size; i++) {
1601            assertEquals("wrong element at position " + i + ",", ll.get(i), al
1602                    .get(i));
1603        }
1604    }
1605
1606    /**
1607     * @tests java.util.Collections#synchronizedCollection(java.util.Collection)
1608     */
1609    @TestTargetNew(
1610        level = TestLevel.COMPLETE,
1611        notes = "",
1612        method = "synchronizedCollection",
1613        args = {java.util.Collection.class}
1614    )
1615    public void test_synchronizedCollectionLjava_util_Collection() {
1616        // Test for method java.util.Collection
1617        // java.util.Collections.synchronizedCollection(java.util.Collection)
1618
1619        LinkedList smallList = new LinkedList();
1620        for (int i = 0; i < 50; i++) {
1621            smallList.add(objArray[i]);
1622        }
1623
1624        final int numberOfLoops = 200;
1625        Collection synchCol = Collections.synchronizedCollection(smallList);
1626        // Replacing the previous line with the line below *should* cause the
1627        // test to fail--the collecion below isn't synchronized
1628        // Collection synchCol = smallList;
1629
1630        SynchCollectionChecker normalSynchChecker = new SynchCollectionChecker(
1631                synchCol, false, numberOfLoops);
1632        SynchCollectionChecker offsetSynchChecker = new SynchCollectionChecker(
1633                synchCol, true, numberOfLoops);
1634        Thread normalThread = new Thread(normalSynchChecker);
1635        Thread offsetThread = new Thread(offsetSynchChecker);
1636        normalThread.start();
1637        offsetThread.start();
1638        while ((normalSynchChecker.getNumberOfChecks() < numberOfLoops)
1639                || (offsetSynchChecker.getNumberOfChecks() < numberOfLoops)) {
1640            try {
1641                Thread.sleep(10);
1642            } catch (InterruptedException e) {
1643            }
1644        }
1645        assertTrue("Returned collection corrupted by multiple thread access",
1646                normalSynchChecker.getResult()
1647                        && offsetSynchChecker.getResult());
1648        try {
1649            normalThread.join(5000);
1650            offsetThread.join(5000);
1651        } catch (InterruptedException e) {
1652            fail("join() interrupted");
1653        }
1654
1655        synchCol.add(null);
1656        assertTrue("Trying to use nulls in collection failed", synchCol
1657                .contains(null));
1658
1659        smallList = new LinkedList();
1660        for (int i = 0; i < 100; i++) {
1661            smallList.add(objArray[i]);
1662        }
1663        new Support_CollectionTest("", Collections
1664                .synchronizedCollection(smallList)).runTest();
1665    }
1666
1667    /**
1668     * @tests java.util.Collections#synchronizedList(java.util.List)
1669     */
1670    @TestTargetNew(
1671        level = TestLevel.COMPLETE,
1672        notes = "",
1673        method = "synchronizedList",
1674        args = {java.util.List.class}
1675    )
1676    public void test_synchronizedListLjava_util_List() {
1677        try {
1678            Collections.synchronizedList(null);
1679            fail("Expected NullPointerException for null list parameter");
1680        } catch (NullPointerException e) {
1681        }
1682
1683        // test with a Sequential Access List
1684        List smallList = new LinkedList();
1685        testSynchronizedList(smallList, "Sequential Access");
1686
1687        smallList = new LinkedList();
1688        List myList;
1689        for (int i = 0; i < 100; i++) {
1690            smallList.add(objArray[i]);
1691        }
1692        myList = Collections.synchronizedList(smallList);
1693        new Support_ListTest("", myList).runTest();
1694
1695        // test with a Random Access List
1696        smallList = new ArrayList();
1697        testSynchronizedList(smallList, "Random Access");
1698
1699        smallList = new ArrayList();
1700        for (int i = 0; i < 100; i++) {
1701            smallList.add(objArray[i]);
1702        }
1703        myList = Collections.synchronizedList(smallList);
1704        new Support_ListTest("", myList).runTest();
1705    }
1706
1707    private void testSynchronizedList(List smallList, String type) {
1708        for (int i = 0; i < 50; i++) {
1709            smallList.add(objArray[i]);
1710        }
1711        final int numberOfLoops = 200;
1712        List synchList = Collections.synchronizedList(smallList);
1713        if (type.equals("Random Access"))
1714            assertTrue(
1715                    "Returned synchronized list should implement the Random Access interface",
1716                    synchList instanceof RandomAccess);
1717        else
1718            assertTrue(
1719                    "Returned synchronized list should not implement the Random Access interface",
1720                    !(synchList instanceof RandomAccess));
1721
1722        // Replacing the previous line with the line below *should* cause the
1723        // test to fail--the list below isn't synchronized
1724        // List synchList = smallList;
1725        SynchCollectionChecker normalSynchChecker = new SynchCollectionChecker(
1726                synchList, false, numberOfLoops);
1727        SynchCollectionChecker offsetSynchChecker = new SynchCollectionChecker(
1728                synchList, true, numberOfLoops);
1729        Thread normalThread = new Thread(normalSynchChecker);
1730        Thread offsetThread = new Thread(offsetSynchChecker);
1731        normalThread.start();
1732        offsetThread.start();
1733        while ((normalSynchChecker.getNumberOfChecks() < numberOfLoops)
1734                || (offsetSynchChecker.getNumberOfChecks() < numberOfLoops)) {
1735            try {
1736                Thread.sleep(10);
1737            } catch (InterruptedException e) {
1738            }
1739        }
1740        assertTrue(
1741                type
1742                        + " list tests: Returned list corrupted by multiple thread access",
1743                normalSynchChecker.getResult()
1744                        && offsetSynchChecker.getResult());
1745        try {
1746            normalThread.join(5000);
1747            offsetThread.join(5000);
1748        } catch (InterruptedException e) {
1749            fail(type + " list tests: join() interrupted");
1750        }
1751        synchList.set(25, null);
1752        assertNull(type + " list tests: Trying to use nulls in list failed",
1753                synchList.get(25));
1754    }
1755
1756    /**
1757     * @tests java.util.Collections#synchronizedMap(java.util.Map)
1758     */
1759    @TestTargetNew(
1760        level = TestLevel.COMPLETE,
1761        notes = "",
1762        method = "synchronizedMap",
1763        args = {java.util.Map.class}
1764    )
1765    public void test_synchronizedMapLjava_util_Map() {
1766        // Test for method java.util.Map
1767        // java.util.Collections.synchronizedMap(java.util.Map)
1768        HashMap smallMap = new HashMap();
1769        for (int i = 0; i < 50; i++) {
1770            smallMap.put(objArray[i], objArray[i]);
1771        }
1772
1773        final int numberOfLoops = 200;
1774        Map synchMap = Collections.synchronizedMap(smallMap);
1775        // Replacing the previous line with the line below should cause the test
1776        // to fail--the list below isn't synchronized
1777        // Map synchMap = smallMap;
1778
1779        SynchMapChecker normalSynchChecker = new SynchMapChecker(synchMap,
1780                false, numberOfLoops);
1781        SynchMapChecker offsetSynchChecker = new SynchMapChecker(synchMap,
1782                true, numberOfLoops);
1783        Thread normalThread = new Thread(normalSynchChecker);
1784        Thread offsetThread = new Thread(offsetSynchChecker);
1785        normalThread.start();
1786        offsetThread.start();
1787        while ((normalSynchChecker.getNumberOfChecks() < numberOfLoops)
1788                || (offsetSynchChecker.getNumberOfChecks() < numberOfLoops)) {
1789            try {
1790                Thread.sleep(10);
1791            } catch (InterruptedException e) {
1792            }
1793        }
1794        assertTrue("Returned map corrupted by multiple thread access",
1795                normalSynchChecker.getResult()
1796                        && offsetSynchChecker.getResult());
1797        try {
1798            normalThread.join(5000);
1799            offsetThread.join(5000);
1800        } catch (InterruptedException e) {
1801            fail("join() interrupted");
1802        }
1803
1804        // synchronized map does not have to permit null keys or values
1805        synchMap.put(new Long(25), null);
1806        synchMap.put(null, new Long(30));
1807        assertNull("Trying to use a null value in map failed", synchMap
1808                .get(new Long(25)));
1809        assertTrue("Trying to use a null key in map failed", synchMap.get(null)
1810                .equals(new Long(30)));
1811
1812        smallMap = new HashMap();
1813        for (int i = 0; i < 100; i++) {
1814            smallMap.put(objArray[i].toString(), objArray[i]);
1815        }
1816        synchMap = Collections.synchronizedMap(smallMap);
1817        new Support_UnmodifiableMapTest("", synchMap).runTest();
1818        synchMap.keySet().remove(objArray[50].toString());
1819        assertNull(
1820                "Removing a key from the keySet of the synchronized map did not remove it from the synchronized map: ",
1821                synchMap.get(objArray[50].toString()));
1822        assertNull(
1823                "Removing a key from the keySet of the synchronized map did not remove it from the original map",
1824                smallMap.get(objArray[50].toString()));
1825    }
1826
1827    /**
1828     * @tests java.util.Collections#synchronizedSet(java.util.Set)
1829     */
1830    @TestTargetNew(
1831        level = TestLevel.COMPLETE,
1832        notes = "",
1833        method = "synchronizedSet",
1834        args = {java.util.Set.class}
1835    )
1836    public void test_synchronizedSetLjava_util_Set() {
1837        // Test for method java.util.Set
1838        // java.util.Collections.synchronizedSet(java.util.Set)
1839        HashSet smallSet = new HashSet();
1840        for (int i = 0; i < 50; i++) {
1841            smallSet.add(objArray[i]);
1842        }
1843
1844        final int numberOfLoops = 200;
1845        Set synchSet = Collections.synchronizedSet(smallSet);
1846        // Replacing the previous line with the line below should cause the test
1847        // to fail--the set below isn't synchronized
1848        // Set synchSet = smallSet;
1849
1850        SynchCollectionChecker normalSynchChecker = new SynchCollectionChecker(
1851                synchSet, false, numberOfLoops);
1852        SynchCollectionChecker offsetSynchChecker = new SynchCollectionChecker(
1853                synchSet, true, numberOfLoops);
1854        Thread normalThread = new Thread(normalSynchChecker);
1855        Thread offsetThread = new Thread(offsetSynchChecker);
1856        normalThread.start();
1857        offsetThread.start();
1858        while ((normalSynchChecker.getNumberOfChecks() < numberOfLoops)
1859                || (offsetSynchChecker.getNumberOfChecks() < numberOfLoops)) {
1860            try {
1861                Thread.sleep(10);
1862            } catch (InterruptedException e) {
1863            }
1864        }
1865        assertTrue("Returned set corrupted by multiple thread access",
1866                normalSynchChecker.getResult()
1867                        && offsetSynchChecker.getResult());
1868        try {
1869            normalThread.join(5000);
1870            offsetThread.join(5000);
1871        } catch (InterruptedException e) {
1872            fail("join() interrupted");
1873        }
1874
1875        Set mySet = Collections.synchronizedSet(smallSet);
1876        mySet.add(null);
1877        assertTrue("Trying to use nulls in list failed", mySet.contains(null));
1878
1879        smallSet = new HashSet();
1880        for (int i = 0; i < 100; i++) {
1881            smallSet.add(objArray[i]);
1882        }
1883        new Support_SetTest("", Collections.synchronizedSet(smallSet))
1884                .runTest();
1885    }
1886
1887    /**
1888     * @tests java.util.Collections#synchronizedSortedMap(java.util.SortedMap)
1889     */
1890    @TestTargetNew(
1891        level = TestLevel.COMPLETE,
1892        notes = "",
1893        method = "synchronizedSortedMap",
1894        args = {java.util.SortedMap.class}
1895    )
1896    public void test_synchronizedSortedMapLjava_util_SortedMap() {
1897        // Test for method java.util.SortedMap
1898        // java.util.Collections.synchronizedSortedMap(java.util.SortedMap)
1899        TreeMap smallMap = new TreeMap();
1900        for (int i = 0; i < 50; i++) {
1901            smallMap.put(objArray[i], objArray[i]);
1902        }
1903
1904        final int numberOfLoops = 200;
1905        Map synchMap = Collections.synchronizedMap(smallMap);
1906        // Replacing the previous line with the line below should cause the test
1907        // to fail--the list below isn't synchronized
1908        // Map synchMap = smallMap;
1909
1910        SynchMapChecker normalSynchChecker = new SynchMapChecker(synchMap,
1911                false, numberOfLoops);
1912        SynchMapChecker offsetSynchChecker = new SynchMapChecker(synchMap,
1913                true, numberOfLoops);
1914        Thread normalThread = new Thread(normalSynchChecker);
1915        Thread offsetThread = new Thread(offsetSynchChecker);
1916        normalThread.start();
1917        offsetThread.start();
1918        while ((normalSynchChecker.getNumberOfChecks() < numberOfLoops)
1919                || (offsetSynchChecker.getNumberOfChecks() < numberOfLoops)) {
1920            try {
1921                Thread.sleep(10);
1922            } catch (InterruptedException e) {
1923            }
1924        }
1925        assertTrue("Returned map corrupted by multiple thread access",
1926                normalSynchChecker.getResult()
1927                        && offsetSynchChecker.getResult());
1928        try {
1929            normalThread.join(5000);
1930            offsetThread.join(5000);
1931        } catch (InterruptedException e) {
1932            fail("join() interrupted");
1933        }
1934
1935        smallMap = new TreeMap();
1936        for (int i = 0; i < 100; i++) {
1937            smallMap.put(objArray[i].toString(), objArray[i]);
1938        }
1939        synchMap = Collections.synchronizedSortedMap(smallMap);
1940        new Support_UnmodifiableMapTest("", synchMap).runTest();
1941        synchMap.keySet().remove(objArray[50].toString());
1942        assertNull(
1943                "Removing a key from the keySet of the synchronized map did not remove it from the synchronized map",
1944                synchMap.get(objArray[50].toString()));
1945        assertNull(
1946                "Removing a key from the keySet of the synchronized map did not remove it from the original map",
1947                smallMap.get(objArray[50].toString()));
1948    }
1949
1950    /**
1951     * @tests java.util.Collections#synchronizedSortedSet(java.util.SortedSet)
1952     */
1953    @TestTargetNew(
1954        level = TestLevel.COMPLETE,
1955        notes = "",
1956        method = "synchronizedSortedSet",
1957        args = {java.util.SortedSet.class}
1958    )
1959    public void test_synchronizedSortedSetLjava_util_SortedSet() {
1960        // Test for method java.util.SortedSet
1961        // java.util.Collections.synchronizedSortedSet(java.util.SortedSet)
1962        TreeSet smallSet = new TreeSet();
1963        for (int i = 0; i < 50; i++) {
1964            smallSet.add(objArray[i]);
1965        }
1966
1967        final int numberOfLoops = 200;
1968        Set synchSet = Collections.synchronizedSet(smallSet);
1969        // Replacing the previous line with the line below should cause the test
1970        // to fail--the list below isn't synchronized
1971        // Set synchSet = smallSet;
1972
1973        SynchCollectionChecker normalSynchChecker = new SynchCollectionChecker(
1974                synchSet, false, numberOfLoops);
1975        SynchCollectionChecker offsetSynchChecker = new SynchCollectionChecker(
1976                synchSet, true, numberOfLoops);
1977        Thread normalThread = new Thread(normalSynchChecker);
1978        Thread offsetThread = new Thread(offsetSynchChecker);
1979        normalThread.start();
1980        offsetThread.start();
1981        while ((normalSynchChecker.getNumberOfChecks() < numberOfLoops)
1982                || (offsetSynchChecker.getNumberOfChecks() < numberOfLoops)) {
1983            try {
1984                Thread.sleep(10);
1985            } catch (InterruptedException e) {
1986            }
1987        }
1988        assertTrue("Returned set corrupted by multiple thread access",
1989                normalSynchChecker.getResult()
1990                        && offsetSynchChecker.getResult());
1991        try {
1992            normalThread.join(5000);
1993            offsetThread.join(5000);
1994        } catch (InterruptedException e) {
1995            fail("join() interrupted");
1996        }
1997    }
1998
1999    /**
2000     * @tests java.util.Collections#unmodifiableCollection(java.util.Collection)
2001     */
2002    @TestTargetNew(
2003        level = TestLevel.COMPLETE,
2004        notes = "",
2005        method = "unmodifiableCollection",
2006        args = {java.util.Collection.class}
2007    )
2008    public void test_unmodifiableCollectionLjava_util_Collection() {
2009        // Test for method java.util.Collection
2010        // java.util.Collections.unmodifiableCollection(java.util.Collection)
2011        boolean exception = false;
2012        Collection c = Collections.unmodifiableCollection(ll);
2013        assertTrue("Returned collection is of incorrect size", c.size() == ll
2014                .size());
2015        Iterator i = ll.iterator();
2016        while (i.hasNext())
2017            assertTrue("Returned list missing elements", c.contains(i.next()));
2018        try {
2019            c.add(new Object());
2020        } catch (UnsupportedOperationException e) {
2021            exception = true;
2022            // Correct
2023        }
2024        if (!exception) {
2025            fail("Allowed modification of collection");
2026        }
2027
2028        try {
2029            c.remove(new Object());
2030            fail("Allowed modification of collection");
2031        } catch (UnsupportedOperationException e) {
2032            // Correct
2033        }
2034
2035        Collection myCollection = new ArrayList();
2036        myCollection.add(new Integer(20));
2037        myCollection.add(null);
2038        c = Collections.unmodifiableCollection(myCollection);
2039        assertTrue("Collection should contain null", c.contains(null));
2040        assertTrue("Collection should contain Integer(20)", c
2041                .contains(new Integer(20)));
2042
2043        myCollection = new ArrayList();
2044        for (int counter = 0; counter < 100; counter++) {
2045            myCollection.add(objArray[counter]);
2046        }
2047        new Support_UnmodifiableCollectionTest("", Collections
2048                .unmodifiableCollection(myCollection)).runTest();
2049    }
2050
2051    /**
2052     * @tests java.util.Collections#unmodifiableList(java.util.List)
2053     */
2054    @TestTargetNew(
2055        level = TestLevel.COMPLETE,
2056        notes = "",
2057        method = "unmodifiableList",
2058        args = {java.util.List.class}
2059    )
2060    public void test_unmodifiableListLjava_util_List() {
2061        // Test for method java.util.List
2062        // java.util.Collections.unmodifiableList(java.util.List)
2063
2064        // test with a Sequential Access List
2065        boolean exception = false;
2066        List c = Collections.unmodifiableList(ll);
2067        // Ensure a NPE is thrown if the list is NULL
2068        try {
2069            Collections.unmodifiableList(null);
2070            fail("Expected NullPointerException for null list parameter");
2071        } catch (NullPointerException e) {
2072        }
2073
2074        assertTrue("Returned list is of incorrect size", c.size() == ll.size());
2075        assertTrue(
2076                "Returned List should not implement Random Access interface",
2077                !(c instanceof RandomAccess));
2078
2079        Iterator i = ll.iterator();
2080        while (i.hasNext())
2081            assertTrue("Returned list missing elements", c.contains(i.next()));
2082        try {
2083            c.add(new Object());
2084        } catch (UnsupportedOperationException e) {
2085            exception = true;
2086            // Correct
2087        }
2088        if (!exception) {
2089            fail("Allowed modification of list");
2090        }
2091
2092        try {
2093            c.remove(new Object());
2094            fail("Allowed modification of list");
2095        } catch (UnsupportedOperationException e) {
2096            // Correct
2097        }
2098
2099        // test with a Random Access List
2100        List smallList = new ArrayList();
2101        smallList.add(null);
2102        smallList.add("yoink");
2103        c = Collections.unmodifiableList(smallList);
2104        assertNull("First element should be null", c.get(0));
2105        assertTrue("List should contain null", c.contains(null));
2106        assertTrue(
2107                "T1. Returned List should implement Random Access interface",
2108                c instanceof RandomAccess);
2109
2110        smallList = new ArrayList();
2111        for (int counter = 0; counter < 100; counter++) {
2112            smallList.add(objArray[counter]);
2113        }
2114        List myList = Collections.unmodifiableList(smallList);
2115        assertTrue("List should not contain null", !myList.contains(null));
2116        assertTrue(
2117                "T2. Returned List should implement Random Access interface",
2118                myList instanceof RandomAccess);
2119
2120        assertTrue("get failed on unmodifiable list", myList.get(50).equals(
2121                new Integer(50)));
2122        ListIterator listIterator = myList.listIterator();
2123        for (int counter = 0; listIterator.hasNext(); counter++) {
2124            assertTrue("List has wrong elements", ((Integer) listIterator
2125                    .next()).intValue() == counter);
2126        }
2127        new Support_UnmodifiableCollectionTest("", smallList).runTest();
2128    }
2129
2130    /**
2131     * @tests java.util.Collections#unmodifiableMap(java.util.Map)
2132     */
2133    @TestTargetNew(
2134        level = TestLevel.COMPLETE,
2135        notes = "",
2136        method = "unmodifiableMap",
2137        args = {java.util.Map.class}
2138    )
2139    public void test_unmodifiableMapLjava_util_Map() {
2140        // Test for method java.util.Map
2141        // java.util.Collections.unmodifiableMap(java.util.Map)
2142        boolean exception = false;
2143        Map c = Collections.unmodifiableMap(hm);
2144        assertTrue("Returned map is of incorrect size", c.size() == hm.size());
2145        Iterator i = hm.keySet().iterator();
2146        while (i.hasNext()) {
2147            Object x = i.next();
2148            assertTrue("Returned map missing elements", c.get(x).equals(
2149                    hm.get(x)));
2150        }
2151        try {
2152            c.put(new Object(), "");
2153        } catch (UnsupportedOperationException e) {
2154            exception = true;
2155            // Correct
2156        }
2157        assertTrue("Allowed modification of map", exception);
2158
2159        exception = false;
2160        try {
2161            c.remove(new Object());
2162        } catch (UnsupportedOperationException e) {
2163            // Correct
2164            exception = true;
2165        }
2166        assertTrue("Allowed modification of map", exception);
2167
2168        exception = false;
2169        Iterator it = c.entrySet().iterator();
2170        Map.Entry entry = (Map.Entry) it.next();
2171        try {
2172            entry.setValue("modified");
2173        } catch (UnsupportedOperationException e) {
2174            // Correct
2175            exception = true;
2176        }
2177        assertTrue("Allowed modification of entry", exception);
2178
2179        exception = false;
2180        Object[] array = c.entrySet().toArray();
2181        try {
2182            ((Map.Entry) array[0]).setValue("modified");
2183        } catch (UnsupportedOperationException e) {
2184            // Correct
2185            exception = true;
2186        }
2187        assertTrue("Allowed modification of array entry", exception);
2188
2189        exception = false;
2190        Map.Entry[] array2 = (Map.Entry[]) c.entrySet().toArray(
2191                new Map.Entry[0]);
2192        try {
2193            array2[0].setValue("modified");
2194        } catch (UnsupportedOperationException e) {
2195            // Correct
2196            exception = true;
2197        }
2198        assertTrue("Allowed modification of array entry2", exception);
2199
2200        HashMap smallMap = new HashMap();
2201        smallMap.put(null, new Long(30));
2202        smallMap.put(new Long(25), null);
2203        Map unmodMap = Collections.unmodifiableMap(smallMap);
2204
2205        assertNull("Trying to use a null value in map failed", unmodMap
2206                .get(new Long(25)));
2207        assertTrue("Trying to use a null key in map failed", unmodMap.get(null)
2208                .equals(new Long(30)));
2209
2210        smallMap = new HashMap();
2211        for (int counter = 0; counter < 100; counter++) {
2212            smallMap.put(objArray[counter].toString(), objArray[counter]);
2213        }
2214        unmodMap = Collections.unmodifiableMap(smallMap);
2215        new Support_UnmodifiableMapTest("", unmodMap).runTest();
2216
2217    }
2218
2219    /**
2220     * @tests java.util.Collections#unmodifiableSet(java.util.Set)
2221     */
2222    @TestTargetNew(
2223        level = TestLevel.COMPLETE,
2224        notes = "",
2225        method = "unmodifiableSet",
2226        args = {java.util.Set.class}
2227    )
2228    public void test_unmodifiableSetLjava_util_Set() {
2229        // Test for method java.util.Set
2230        // java.util.Collections.unmodifiableSet(java.util.Set)
2231        boolean exception = false;
2232        Set c = Collections.unmodifiableSet(s);
2233        assertTrue("Returned set is of incorrect size", c.size() == s.size());
2234        Iterator i = ll.iterator();
2235        while (i.hasNext())
2236            assertTrue("Returned set missing elements", c.contains(i.next()));
2237        try {
2238            c.add(new Object());
2239        } catch (UnsupportedOperationException e) {
2240            exception = true;
2241            // Correct
2242        }
2243        if (!exception) {
2244            fail("Allowed modification of set");
2245        }
2246        try {
2247            c.remove(new Object());
2248            fail("Allowed modification of set");
2249        } catch (UnsupportedOperationException e) {
2250            // Correct
2251        }
2252
2253        Set mySet = Collections.unmodifiableSet(new HashSet());
2254        assertTrue("Should not contain null", !mySet.contains(null));
2255        mySet = Collections.unmodifiableSet(Collections.singleton(null));
2256        assertTrue("Should contain null", mySet.contains(null));
2257
2258        mySet = new TreeSet();
2259        for (int counter = 0; counter < 100; counter++) {
2260            mySet.add(objArray[counter]);
2261        }
2262        new Support_UnmodifiableCollectionTest("", Collections
2263                .unmodifiableSet(mySet)).runTest();
2264    }
2265
2266    /**
2267     * @tests java.util.Collections#unmodifiableSortedMap(java.util.SortedMap)
2268     */
2269    @TestTargetNew(
2270        level = TestLevel.COMPLETE,
2271        notes = "",
2272        method = "unmodifiableSortedMap",
2273        args = {java.util.SortedMap.class}
2274    )
2275    public void test_unmodifiableSortedMapLjava_util_SortedMap() {
2276        // Test for method java.util.SortedMap
2277        // java.util.Collections.unmodifiableSortedMap(java.util.SortedMap)
2278        boolean exception = false;
2279        TreeMap tm = new TreeMap();
2280        tm.putAll(hm);
2281        Map c = Collections.unmodifiableSortedMap(tm);
2282        assertTrue("Returned map is of incorrect size", c.size() == tm.size());
2283        Iterator i = hm.keySet().iterator();
2284        while (i.hasNext()) {
2285            Object x = i.next();
2286            assertTrue("Returned map missing elements", c.get(x).equals(
2287                    tm.get(x)));
2288        }
2289        try {
2290            c.put(new Object(), "");
2291        } catch (UnsupportedOperationException e) {
2292            exception = true;
2293            // Correct
2294        }
2295
2296        if (!exception) {
2297            fail("Allowed modification of map");
2298        }
2299        try {
2300            c.remove(new Object());
2301        } catch (UnsupportedOperationException e) {
2302            // Correct
2303            return;
2304        }
2305        fail("Allowed modification of map");
2306    }
2307
2308    /**
2309     * @tests java.util.Collections#unmodifiableSortedSet(java.util.SortedSet)
2310     */
2311    @TestTargetNew(
2312        level = TestLevel.COMPLETE,
2313        notes = "",
2314        method = "unmodifiableSortedSet",
2315        args = {java.util.SortedSet.class}
2316    )
2317    public void test_unmodifiableSortedSetLjava_util_SortedSet() {
2318        // Test for method java.util.SortedSet
2319        // java.util.Collections.unmodifiableSortedSet(java.util.SortedSet)
2320        boolean exception = false;
2321        SortedSet ss = new TreeSet();
2322        ss.addAll(s);
2323        SortedSet c = Collections.unmodifiableSortedSet(ss);
2324        assertTrue("Returned set is of incorrect size", c.size() == ss.size());
2325        Iterator i = ll.iterator();
2326        while (i.hasNext())
2327            assertTrue("Returned set missing elements", c.contains(i.next()));
2328        try {
2329            c.add(new Object());
2330        } catch (UnsupportedOperationException e) {
2331            exception = true;
2332            // Correct
2333        }
2334        if (!exception) {
2335            fail("Allowed modification of set");
2336        }
2337        try {
2338            c.remove(new Object());
2339        } catch (UnsupportedOperationException e) {
2340            // Correct
2341            return;
2342        }
2343        fail("Allowed modification of set");
2344    }
2345
2346    /**
2347     * Test unmodifiable objects toString methods
2348     */
2349    @TestTargets({
2350        @TestTargetNew(
2351            level = TestLevel.PARTIAL_COMPLETE,
2352            notes = "",
2353            method = "toString",
2354            args = {}
2355        ),
2356        @TestTargetNew(
2357            level = TestLevel.PARTIAL_COMPLETE,
2358            notes = "",
2359            method = "unmodifiableCollection",
2360            args = {java.util.Collection.class}
2361        ),
2362        @TestTargetNew(
2363            level = TestLevel.PARTIAL_COMPLETE,
2364            notes = "",
2365            method = "unmodifiableMap",
2366            args = {java.util.Map.class}
2367        )
2368    })
2369    public void test_unmodifiable_toString_methods() {
2370        // Regression for HARMONY-552
2371        ArrayList al = new ArrayList();
2372        al.add("a");
2373        al.add("b");
2374        Collection uc = Collections.unmodifiableCollection(al);
2375        assertEquals("[a, b]", uc.toString());
2376        HashMap m = new HashMap();
2377        m.put("one", "1");
2378        m.put("two", "2");
2379        Map um = Collections.unmodifiableMap(m);
2380        assertTrue("{one=1, two=2}".equals(um.toString()) ||
2381                   "{two=2, one=1}".equals(um.toString()));
2382    }
2383
2384
2385    @TestTargetNew(
2386        level = TestLevel.COMPLETE,
2387        notes = "",
2388        method = "singletonList",
2389        args = {java.lang.Object.class}
2390    )
2391    public void test_singletonListLjava_lang_Object() {
2392        // Test for method java.util.Set
2393        // java.util.Collections.singleton(java.lang.Object)
2394        String str = "Singleton";
2395
2396        List single = Collections.singletonList(str);
2397        assertEquals(1, single.size());
2398        assertTrue(single.contains(str));
2399        assertFalse(single.contains(null));
2400        assertFalse(Collections.singletonList(null).contains(str));
2401        assertTrue(Collections.singletonList(null).contains(null));
2402
2403        try {
2404            single.add("New element");
2405            fail("UnsupportedOperationException expected");
2406        } catch (UnsupportedOperationException e) {
2407            //expected
2408        }
2409    }
2410
2411    @TestTargetNew(
2412        level = TestLevel.COMPLETE,
2413        notes = "",
2414        method = "singletonMap",
2415        args = {java.lang.Object.class, java.lang.Object.class}
2416    )
2417    public void test_singletonMapLjava_lang_Object() {
2418        // Test for method java.util.Set
2419        // java.util.Collections.singleton(java.lang.Object)
2420        Double key = new Double (3.14);
2421        String value = "Fundamental constant";
2422
2423        Map single = Collections.singletonMap(key, value);
2424        assertEquals(1, single.size());
2425        assertTrue(single.containsKey(key));
2426        assertTrue(single.containsValue(value));
2427        assertFalse(single.containsKey(null));
2428        assertFalse(single.containsValue(null));
2429        assertFalse(Collections.singletonMap(null, null).containsKey(key));
2430        assertFalse(Collections.singletonMap(null, null).containsValue(value));
2431        assertTrue(Collections.singletonMap(null, null).containsKey(null));
2432        assertTrue(Collections.singletonMap(null, null).containsValue(null));
2433
2434        try {
2435            single.clear();
2436            fail("UnsupportedOperationException expected");
2437        } catch (UnsupportedOperationException e) {
2438            //expected
2439        }
2440
2441        try {
2442            single.put(new Double(1), "one wrong value");
2443            fail("UnsupportedOperationException expected");
2444        } catch (UnsupportedOperationException e) {
2445            //expected
2446        }
2447    }
2448
2449    /**
2450     * Sets up the fixture, for example, open a network connection. This method
2451     * is called before a test is executed.
2452     */
2453    protected void setUp() {
2454        objArray = new Object[1000];
2455        myobjArray = new Object[1000];
2456        for (int i = 0; i < objArray.length; i++) {
2457            objArray[i] = new Integer(i);
2458            myobjArray[i] = new MyInt(i);
2459        }
2460
2461        ll = new LinkedList();
2462        myll = new LinkedList();
2463        s = new HashSet();
2464        mys = new HashSet();
2465        reversedLinkedList = new LinkedList(); // to be sorted in reverse order
2466        myReversedLinkedList = new LinkedList(); // to be sorted in reverse
2467        // order
2468        hm = new HashMap();
2469        for (int i = 0; i < objArray.length; i++) {
2470            ll.add(objArray[i]);
2471            myll.add(myobjArray[i]);
2472            s.add(objArray[i]);
2473            mys.add(myobjArray[i]);
2474            reversedLinkedList.add(objArray[objArray.length - i - 1]);
2475            myReversedLinkedList.add(myobjArray[myobjArray.length - i - 1]);
2476            hm.put(objArray[i].toString(), objArray[i]);
2477        }
2478    }
2479
2480    /**
2481     * Tears down the fixture, for example, close a network connection. This
2482     * method is called after a test is executed.
2483     */
2484    protected void tearDown() {
2485        objArray = null;
2486        myobjArray = null;
2487
2488        ll = null;
2489        myll = null;
2490        reversedLinkedList = null;
2491        myReversedLinkedList = null;
2492        s = null;
2493        mys = null;
2494        hm = null;
2495    }
2496
2497    protected void doneSuite() {
2498        objArray = null;
2499    }
2500}
2501