// 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[] evens = {2, 4, 6, 8, 10, 12, 14}; String[] taylor = {"we", "never", "go", "out", "of", "style"}; // we wrote a method to sum a list: System.out.println("sum of evens = " + sum(evens)); // and explored this "array mystery" mystery(); // we used Arrays.toString to print array contents: System.out.println("evens = " + Arrays.toString(evens)); // In exploring value semantics vs reference semantics, we saw that // this swap method did not change the values of x and y int x = 8; int y = 24; 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 modified list2 // 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(evens); System.out.println("after reverse, evens = " + Arrays.toString(evens)); } // 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}; // we pulled this array out in the debugger in presentation view to watch it change 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[] list) { list[0] = -924; list[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) // this works for both odd and even length lists (try 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; } } }