TestArrays.java
Select all
/* TestArrays.java CIS 260 2/16/2005 David Klick Demonstrates various methods of the Arrays and Collections classes. Note: This program requires Java 1.5 or later to compile. */ import java.util.*; public class TestArrays { public static void main(String[] args) { int pos; Integer[] a1 = { new Integer(78), new Integer(10), new Integer(-3), new Integer(9), new Integer(17), new Integer(88), new Integer(29), new Integer(32), new Integer(31), new Integer(-4) }; Integer[] a2 = new Integer[a1.length]; Integer[] a3 = new Integer[a1.length]; System.arraycopy(a1, 0, a2, 0, a1.length); Arrays.fill(a3, 16); System.out.println("a1: " + Arrays.toString(a1)); System.out.println("a2: " + Arrays.toString(a2)); System.out.println("a3: " + Arrays.toString(a3)); if (Arrays.equals(a1, a2)) { System.out.println("a1 and a2 are equal"); } else { System.out.println("a1 and a2 are not equal"); } if (Arrays.equals(a1, a3)) { System.out.println("a1 and a3 are equal"); } else { System.out.println("a1 and a3 are not equal"); } // new generics notation restricts contents of List List
lst = new ArrayList
(Arrays.asList(a1)); System.out.println("a1 max: " + Collections.max(lst)); System.out.println("a1 min: " + Collections.min(lst)); Collections.sort(lst); lst.toArray(a1); System.out.println("This list should be in sorted order:"); System.out.println("a1: " + Arrays.toString(a1)); pos = Arrays.binarySearch(a1, 88); if (pos > -1) { System.out.println("88 found in a1 at position " + pos); } else { System.out.println("88 not found in a1"); } pos = Arrays.binarySearch(a1, -4); if (pos > -1) { System.out.println("-4 found in a1 at position " + pos); } else { System.out.println("-4 not found in a1 at position " + pos); } pos = Arrays.binarySearch(a1, 70); if (pos > -1) { System.out.println("70 found in a1 at postion " + pos); } else { System.out.println("70 not found in a1"); } Collections.reverse(lst); System.out.println("The list should now be reversed"); System.out.println("a1 reversed: " + Arrays.toString(lst.toArray())); Collections.shuffle(lst); System.out.println("The list should now be shuffled"); System.out.println("a1 shuffled: " + Arrays.toString(lst.toArray())); } } /* Sample output: a1: [78, 10, -3, 9, 17, 88, 29, 32, 31, -4] a2: [78, 10, -3, 9, 17, 88, 29, 32, 31, -4] a3: [16, 16, 16, 16, 16, 16, 16, 16, 16, 16] a1 and a2 are equal a1 and a3 are not equal a1 max: 88 a1 min: -4 This list should be in sorted order: a1: [-4, -3, 9, 10, 17, 29, 31, 32, 78, 88] 88 found in a1 at position 9 -4 found in a1 at position 0 70 not found in a1 The list should now be reversed a1 reversed: [88, 78, 32, 31, 29, 17, 10, 9, -3, -4] The list should now be shuffled a1 shuffled: [88, 31, 29, 78, -4, 17, 32, 9, -3, 10] */