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