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