// This class contains several small examples of array manipulation. Each // is written as a method. import java.util.*; public class ArraySample1 { public static void main(String[] args) { // below are two examples of an array initializer int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23}; String[] words = {"four", "score", "and", "seven", "years", "ago"}; // we wrote a method to sum a list: System.out.println("sum of primes = " + sum(primes)); // and explored this "array mystery" mystery(); // we used Arrays.toString to print array contents: System.out.println("primes = " + Arrays.toString(primes)); // In exploring value semantics vs reference semantics, we saw that // this swap method did not change the values of x and y int x = 3; int y = 7; swap(x, y); // we saw that we can have two variables that both refer to the same // array object: int[] list1 = {8, 17, 4, 93}; int[] list2 = list1; list2[0] = -98; System.out.println("list1 = " + Arrays.toString(list1)); // notice that list1 has changed even though we changed list2[0] // we saw that the method call below changed the contents of the array modify(list1); System.out.println("after modify, list1 = " + Arrays.toString(list1)); // and we wrote this method for reversing the contents of the array reverse(primes); System.out.println("after reverse, primes = " + Arrays.toString(primes)); } // an example of an array mystery problem--there will a problem like this // on the final public static void mystery() { int[] a = {1, 7, 5, 6, 4, 14, 11}; for (int i = 0; i < a.length - 1; i++) { if (a[i] > a[i + 1]) { a[i + 1] = a[i + 1] * 2; } } System.out.println("mystery array = " + Arrays.toString(a)); } // we saw that this is correct code for swapping two int values, but it // only swaps the local copies of these values and has no effect on any // variables that are used in calling the method public static void swap(int x, int y) { int temp = x; x = y; y = temp; } // we saw that this method was able to change the array contents because // of reference semantics public static void modify(int[] a) { a[0] = -924; a[1] = -42; } // this method was written using the standard loop traversal pattern public static int sum(int[] data) { int sum = 0; // traversal pattern for (int i = 0; i < data.length; i++) { // do something with data[i] sum = sum + data[i]; } return sum; } // this method reverses the sequence of values in an array public static void reverse(int[] list) { // we found that we only wanted to do the swapping for half of the // length of the list (otherwise we unreversed it) for (int i = 0; i < list.length / 2; i++) { // compute the index for the other value to swap int j = list.length - 1 - i; // swap two values int temp = list[i]; list[i] = list[j]; list[j] = temp; } } }