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