ARRAYS Spring 2019
ARRAY BASICS An array is an indexed collection of data elements of the same type Indexed means that the elements are numbered (starting at 0) The restriction of the same type is important, as arrays are stored in consecutive memory cells. By making sure they are the same type, you also make sure they are of the same size
CREATING ARRAYS Two steps: 1. Declare an array variable 2. Create the array (with the operator new) Formats for declaring the array variable: type[] arrayname; type arrayname[]; Format for creating the array: arrayname = new type[size]; Examples: int[] list; list = new int[30]; //preferred //alternate //declare the array variable list //creates an array of 30 integers double[] num; nums = new double[x]; //declare the array variable nums //creates an array of x doubles
CREATING ARRAYS CONT. Combined format: type[] arrayname = new type[size]; Examples: int[] list = new int[30]; char[] name = new char[20]; double[] nums = new double[x]; Notice that the size can be a variable, as all arrays are created dynamically in Java The array s size is stored in arrayname.length. For example, the size of the array named list is: list.length
INITIALIZING AND USING ARRAYS When an array of a built-in type is created, elements are initialized automatically numeric types elements are all 0 char type elements initialized to Unicode 0, \0, \u0000 boolean type each element is false Here is an example illustrating automatic initialization Once created, reference a specific element at a given index position using arrayname[index] Array indices go from 0 to (array.length - 1) The index must be an integer or integer expression Examples: int x; int[] list = new int[5]; // create array double[] nums = new double[10]; // create array list[3] = 6; // assign value 6 to array item at index 3 System.out.print(nums[2]); // output array item with index 2 list[x] = list[x+1]; // set values in list array to {1, 3, 5, 7, 9} for (int i = 0; i < list.length; i++) list[i] = i * 2 + 1;
INITIALIZER LISTS You can declare, create, and initialize an array in one line (in this case, the new operation is implicit): type[] arrayname = { initializer list }; The initializer list is a comma-separated list of array values. The compiler determines the number of elements in the array using this list. Examples: int[] list = {2, 4, 6, 8, 10, 12, 14, 16}; // has size 8 double[] grades = {96.5, 88.4, 90.3, 70.1}; // has size 4 char[] vowels = {'a', 'e', 'i', 'o', 'u'}; // size 5
PASSING ARRAYS Array variables can be used as method parameters The arrays themselves are not passed by value; but their reference variables are Regular parameters (of built-in primitive types) are passed by value When passing an array into a function, only the array reference variable is passed in A copy of the array is not made, just a copy of the reference variable Parameter variable refers to the original array, so changes to the array in the method will affect the original array Assigning a new array to the reference variable inside the method will not change the original reference variable/array Note: Pass-by-value vs. pass-by-reference is a complicated subject when discussing Java. Technically, all Java parameters are passed by value, but because all non-primitives are dynamically allocated, it leads to semantics that are very similar to pass-by-reference in a lot of cases, but not all. See here for one explanation if you re curious. Or here
COPYING ARRAYS Given two arrays, copying the contents of one to the other is slightly more complicated than dealing with primitive types. For example, if we have these two arrays: int[] list1 = new int[5]; int[] list2 = {3, 5, 7, 9, 11}; Then this notation does NOT copy the array contents: list1 = list2; We must copy element-by-element. For loops are an easy and common way to do this: for (int i = 0; i < list2.length; i++) list1[i] = list2[i]; We can also use the arraycopy method in the java.lang.system class. It has the format: arraycopy(sourcearray, src_pos, targetarray, tar_pos, length); src_pos and tar_pos indicate the starting position to use in the copy process. length is the number of elements to be copied. This call is the same as the for-loop above: System.arraycopy(list2, 0, list1, 0, list2.length);
MULTI-DIMENSIONAL ARRAYS For multi-dimensional arrays, you use a different set of index brackets for each dimension Remember that multi-dimensional arrays are effectively arrays of arrays For a 2d array, we often think of the first index as rows and the second as columns, but all that matters is being consistent. So, when using a multi-dimensional array, make sure that the indices are always used in the same order. int[][] table = new int[5][3]; short[][] matrix = { {3, 4, 5}, {1, 2, 3}, {0, 5, 9}, // a 5 x 3 table of integers {8, 1, -2} }; // a 4 x 3 matrix of short integers table[3][1] = 5; // assigns a 5 to "row 3, column 1", in one interpretation Examples copying arrays and using 2D arrays
ENHANCED for LOOPS The enhanced for statement allows us to iterate through any array or collection without using a counter (added in Java 1.5) Note that using this version of a for loop is always good for ACCESSING array elements, but not always useful for MODIFYING the array elements There are some cases where it is possible (when the elements in the array/collection are mutable objects and you are using member functions to change them), but you may not change primitives or use assignment statements to change the elements As a general rule, use an enhanced for loop if you are looping in the first-to-last element order, do not need the loop index, and do not need to do any assignment to the array elements or change an immutable object. Format (for arrays): for ( parameter : arrayname ) Loop body
ENHANCED for LOOPS This, a typical loop for adding up the elements of an array: int [] values = new int[10]; //More statements to load the array int total = 0; for (int i = 0; i < values.length; i++) total = total + values[i]; System.out.println( The total is + total); Is equivalent to this, using an enhanced for loop. int[] values = new int[10]; // other statements that load array with data... int total = 0; for (int number : values) total = total + number; System.out.println("The total is " + total); Array3.java code example using enhanced for loops
VARIABLE-LENGTH PARAMETER LISTS A method can have an unspecified number of arguments of a specified type (this feature was also added in Java 1.5) To do this, follow the type name with an ellipsis ( ) typename variablename The use of the ellipsis can only occur once in a parameter list and it must be at the end, similar to default parameters in C++ void dotask(int x, double... values) // LEGAL void dothing(double... values, int size) void dothing(double... values, int... numbers) // ILLEGAL // ILLEGAL In the legal dotask method above, a variable number of arguments may be passed in. These are all legal calls: double d1, d2, d3, d4; //some assignment statements to the variables dotask(5, d1, d2); dotask(5, d1, d2, d3); dotask(5, d1, d2, d3, d4); dotask(5, d1, d2, d3, d4, 3.4, 5.9, 12.4);
VARIABLE-LENGTH PARAMETER LISTS Java treats a variable-length list of arguments like an array of items of the same type. These are often handled using for loops. Since they are arrays, enhanced for loops can be used on them, as well. void printstats(double values) { for (double val: values) System.out.print(val + ); } Example
EXAMPLES I will often provide a link to the code examples from the book that are related to the notes. I will sometimes go through some of them in class, but most are just there for your reference. One thing of note in this set is shown in example 7.7 (fig07_07). As of Java 7, Java will ignore underscores (_) in numeric literals, so you can use them to make large numbers easier to read. In this example, they use 60_000_000 instead of 60000000, as it makes it more obvious it is 60 million at a glance. Some code examples from Deitel (Chapter 7)