slide1.4_2009 - Module 1.4 Module Arrays Arrays...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Module 1.4 Module Arrays Arrays EE3206/EE5805 Java Programming & Applications EE3206/EE5805 1 Intended Learning Outcomes To To To To To To To To To To To To To To use array to store a collection of elements. recognize the multidimensional form of arrays. understand how an array is passed as an argument. simplify programming using enhanced for loop. copy contents from one array to another. search and sort elements in an array. program with arrays. EE3206/EE5805 Java Programming & Applications EE3206/EE5805 2 Introducing Arrays Array is a data structure that represents a collection of the same types of data. double myList = new double[10]; myList reference myList[0] myList[1] Array reference variable myList[2] myList[3] myList[4] Array element at index 5 myList[5] myList[6] myList[7] myList[8] myList[9] 5.6 4.5 3.3 13.2 4 34.33 34 45.45 99.993 11123 3 Element value EE3206/EE5805 Java Programming & Applications EE3206/EE5805 Declaring & Creating Array To declare an array To datatype arrayRefVar; arrayRefVar Example: double myList; Example: myList This style is allowed, but not preferred This datatype arrayRefVar; ; Example: double myList; myList To create an array To arrayRefVar = new datatype[arraySize]; new datatype[arraySize Example: myList = new double[10]; Example: myList To declare & create in one step To datatype arrayRefVar = new datatype[arraySize]; arrayRefVar new datatype[arraySize Example: double myList = new double[10]; double myList myList[0] references the first element in the array. myList[9] references the last element in the array. EE3206/EE5805 Java Programming & Applications EE3206/EE5805 4 Array On Creation An array’s size is fixed once created An • arrayRefVar.length Default value on creation Default • • • 0 for the numeric primitive data types, for '\u0000' for char types, and for char types, false for boolean types. for boolean types. Array’s elements accessed through index Array • • array indices are 0-based array indexed variable format: arrayRefVar[index]; ndexed arrayRefVar[index • e.g. myList[2] = myList[0] + myList[1]; EE3206/EE5805 Java Programming & Applications EE3206/EE5805 5 Initializing Array Using Shorthand The shorthand notation must be in one statement. double myList = {1.9, 2.9, 3.4, 3.5}; double myList double myList; double myList myList = {1.9, 2.9, 3.4, 3.5}; // correct // only declare // wrong The above shorthand notation is equivalent to the following The statements: statements: double myList = new double[4]; double myList myList[0] = 1.9; myList[1] = 2.9; myList[2] = 3.4; myList[3] = 3.5; myList[3] EE3206/EE5805 Java Programming & Applications EE3206/EE5805 6 Enhanced for Loop Enhanced for Since JDK 1.5, a new for loop is introduced to enable you to traverse the verse complete array sequentially without using an index variable. For example, complete example, the following code displays all elements in the array myList: myList for (double value: myList) System.out.println(value); for (int i=0; i<myList.length; i++) { double value = myList[i]; System.out.println(value); } equivalent In general, the syntax is for (elementType value: arrayRefVar) { value: arrayRefVar // Process the value } The value in the for loop is a copy of the array element copy You still have to use an index variable if you wish to change the elements in You elements the array or traverse the array in a different order. EE3206/EE5805 Java Programming & Applications EE3206/EE5805 7 Example: Testing Arrays Objective: The program receives 6 numbers from the user, finds the largest number and counts the the inds occurrence of the largest number entered. Suppose you entered 3, 5, 2, 5, 5, and 5, the largest number is 5 and its occurrence count is 4. largest TestArray Run EE3206/EE5805 Java Programming & Applications EE3206/EE5805 8 Passing Arrays Java Array itself is an “object” which is a reference type, no matter no what type of elements it contains. what For a parameter of a primitive type: primitive • • The actual value is passed. The Changing the value of the local parameter inside the method does not not affect the value of the variable outside the method. affect For a parameter of an reference type: reference • The value of the parameter is a reference to an array. This reference rence is passed to the method. In other words, a copy of the reference is passed by value passed • Any changes to the array that occur inside the method body will Any affect the original array that was passed as the argument. Do you know why most programming languages prefer passing array by reference? array EE3206/EE5805 Java Programming & Applications EE3206/EE5805 9 Copying Arrays (Shallow Copy) Often, you need to duplicate an array or a part of an array. If you attempt to use the assignment statement (=), as follows: use list2 = list1; Before the assignment list2 = list1; list1 After the assignment list2 = list1; list1 Contents of list1 Contents of list1 list2 list2 Contents of list2 Garbage Contents of list2 Now list2 references to the contents of list1. This is not a real copy. It is also known as Shallow Copy. This It Shallow EE3206/EE5805 Java Programming & Applications EE3206/EE5805 10 Copying Arrays (Deep Copy) In contrast to shallow copy, deep copy duplicates all the elements in In ts an array. an Using a loop: Using int sourceArray = {2, 3, 1, 5, 10}; sourceArray int targetArray = new int[sourceArray.length]; targetArray new int[sourceArray.length for (int i = 0; i < sourceArrays.length; i++) 0; sourceArrays.length targetArray[i] = sourceArray[i]; sourceArray[i Using arraycopy Utility from System Class: arraycopy arraycopy(sourceArray, src_pos, targetArray, tar_pos, length); src_pos targetArray tar_pos Example: System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length); 0, targetArray 0, sourceArray.length EE3206/EE5805 Java Programming & Applications EE3206/EE5805 11 Passing Arrays to Methods We have a method: We public static void printArray(int array) { printArray(int for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } } You may invoke the method like: int list = {3, 1, 2, 6, 4, 2}; printArray(list); Or invoke the method using Anonymous array: printArray(new int{3, 1, 2, 6, 4, 2}); It creates an array using the following syntax: It new dataType{literal0, literal1, ..., literalk} literalk There is no explicit reference variable for the array. Such array is called an is anonymous array. anonymous EE3206/EE5805 Java Programming & Applications EE3206/EE5805 12 Simple Example of Passing Array public class Test { public static void main(String args) { public args int x = 1; // x represents an int value 1; int int y = {1,1,1}; // y represents an array of int values int m(x, y); m(x, // Invoke m with arguments x and y // // output 1 (no change) // output 5555 (changed) System.out.println("x is " + x); System.out.println("y[0] is " + y[0]); } public static void m(int number, int numbers) public m(int number, int number = 1001; // Assign a new number // numbers[0] = 5555; // Assign a new numbers[0] // } } { value to number value to numbers[0] EE3206/EE5805 Java Programming & Applications EE3206/EE5805 13 Call Stack & Heap Call Stack Space required for method m int numbers:reference int number: 1 Space required for the main method int y: reference int x: 1 Heap Array of ten int values is stored here The arrays are stored in a heap. Objects are often bulky, so does an array. Moving them takes many I/O Objects I/O operations that is not preferred and mostly not necessary. operations The JVM stores the array in an area of memory, called heap, which is used heap which for dynamic memory allocation where blocks of memory are allocated and dynamic where freed in an arbitrary order. When invoking m(x, y), the values of x and y are passed to number and m(x, the and are number and numbers. Since y contains the reference value to the array, numbers now numbers Since contains numbers now contains the same reference value to the same array. contains EE3206/EE5805 Java Programming & Applications EE3206/EE5805 14 Example: Passing Arrays as Arguments Example: Passing Objective: Demonstrate differences of passing primitive data type variables and array variables. type Stack Space required for the swap method n2: 2 n1: 1 Space required for the main method int a reference Heap Stack Space required for the swapFirstTwoInArray method int array reference Space required for the main method int a reference a[1]: 2 a[0]: 1 The arrays are stored in a heap. Invoke swap(int n1, int n2). The primitive type values in a[0] and a[1] are passed to the swap method. Invoke swapFirstTwoInArray(int array). The reference value in a is passed to the swapFirstTwoInArray method. Pass by Value Pass by Reference TestPassAray Run EE3206/EE5805 Java Programming & Applications EE3206/EE5805 15 Returning an Array from a Method public static int reverse(int list) { public int int result = new int[list.length]; int[list.length for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { 0, result[j] = list[i]; } return result; } To run these two statements: To int list1 = new int{1, 2, 3, 4, 5, 6}; int list2 = reverse(list1); How many arrays in heap are being referenced now? How EE3206/EE5805 Java Programming & Applications EE3206/EE5805 16 Two-dimensional Arrays // Declare array ref var // var dataType refVar; // Create array and assign its reference to variable // refVar = new dataType[10][10]; // Combine declaration and creation in one statement // dataType refVar = new dataType[10][10]; refVar new // Alternative syntax // dataType refVar = new dataType[10][10]; You can also use an array initializer to declare, create and initialize a twoinitializer dimensional array. For example, int array = { int {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} }; int array array[0][0] = array[0][0] array[0][2] = array[1][1] = array[2][0] = array[2][2] = array[3][1] = = new int[4][3]; 1; array[0][1] = 2; 3; array[1][0] = 4; 5; array[1][2] = 6; 7; array[2][1] = 8; 9; array[3][0] = 10; 11; array[3][2] = 12; Same as EE3206/EE5805 Java Programming & Applications EE3206/EE5805 17 Two-dimensional Array Illustration 01 0 1 2 3 4 matrix = new int[5][5]; 2 3 4 0 1 2 3 4 01 2 3 4 0 1 0 1 4 1 2 5 2 3 6 9 12 7 2 3 7 10 8 11 matrix[2][1] = 7; int array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} }; matrix.length? 5 matrix[0].length? 5 EE3206/EE5805 Java Programming & Applications EE3206/EE5805 array.length? 4 array[0].length? 3 18 Lengths of Two-dimensional Arrays 2D array has two-stage reference 2D int x = new int[3][4]; int x x[0] x[1] x[2] x[2][0] x[2][1] x[2][2] x[2][3] x.length is 3 x[2].length is 4 x[1][0] x[1][1] x[1][2] x[1][3] x[1].length is 4 x[0][0] x[0][1] x[0][2] x[0][3] x[0].length is 4 int array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} }; array.length array[0].length array[1].length array[2].length array[3].length To access array[4].length • Error (ArrayIndexOutOfBoundsException) EE3206/EE5805 Java Programming & Applications EE3206/EE5805 19 Ragged Arrays Each row in a two-dimensional array is itself an array. So, the rows Each So, can have different lengths. Such an array is known as a ragged array. For example, array For matrix.length is 5 matrix[0].length is 5 int matrix = { int matrix[1].length is 4 {1, 2, 3, 4, 5}, {1, matrix[2].length is 3 {2, 3, 4, 5}, matrix[3].length is 2 {3, 4, 5}, matrix[4].length is 1 {4, 5}, {5} 1234 5 int triangleArray = { }; {1, 2, 3, 4, 5}, {2, 3, 4, 5}, {3, 4, 5}, {4, 5}, {5} }; 1234 123 12 12 EE3206/EE5805 Java Programming & Applications EE3206/EE5805 20 Multidimensional Arrays Occasionally, you will need to represent n-dimensional data structures. dimensional In Java, you can create n-dimensional arrays for any integer n. In dimensional The way to declare two-dimensional array variables and create twoThe dimensional arrays can be generalized to declare n-dimensional array dimensional variables and create n-dimensional arrays. For example, the following variables dimensional syntax declares a three-dimensional array variable scores, creates an syntax dimensional array, and assigns its reference to scores. array, double scores = new double[10][5][2]; EE3206/EE5805 Java Programming & Applications EE3206/EE5805 21 Searching Arrays Java provides several overloaded binarySearch methods for searching a key in an array of int, double, char, short, long, and float in the java.util.Arrays class. For example, the following code searches the keys in an array of numbers and an array of characters. If an element exists: int list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79}; System.out.println("Index is " + java.util.Arrays.binarySearch(list, 11)); // Return is 4 If an element does not exist: char chars = {'a', 'c', 'g', 'x', 'y', 'z'}; System.out.println("Index is " + java.util.Arrays.binarySearch(chars, 't')); // Return is –4 // -(insertion point + 1) The array must be pre-sorted in increasing order, otherwise the results are undefined. If the array contains multiple elements with the specified value, there is no guarantee which one will be found. The return value will be >= 0 if and only if the key is found EE3206/EE5805 Java Programming & Applications EE3206/EE5805 22 Sorting Arrays Sorting, like searching, is also a common task in computer programming. Sorting, amming. Many different algorithms have been developed for sorting. The simplest and Many implest intuitive one is selection sort. selection Selection sort algorithm Selection • finds the largest number in the list and places it last, • then finds the largest number remaining and places it next to last • and so on until the list contains only a single number. and Example: Example: int myList = {2, 9, 5, 4, 8, 1, 6}; myList {2, 2 2 2 1 95 65 14 24 4 4 5 5 8 1 6 6 16 2 89 2 89 2 89 14 5 15 4 65 4 // Unsorted // 8 6 6 19 89 89 23 EE3206/EE5805 Java Programming & Applications EE3206/EE5805 Sorting Arrays Since sorting is frequently used in programming, Java provides several overloaded sort methods for sorting an array of int, double, char, short, long, and float in the java.util.Arrays class. For example, the following code sorts an array of numbers and an array of characters. double numbers = {6.0, 4.4, 1.9, 2.9, 3.4, 3.5}; java.util.Arrays.sort(numbers); // no return char chars = {'a', 'A', '4', 'F', 'D', 'P'}; java.util.Arrays.sort(chars); // no return EE3206/EE5805 Java Programming & Applications EE3206/EE5805 24 ...
View Full Document

This note was uploaded on 04/20/2010 for the course ELECTRONIC EE3206 taught by Professor Tingchiwang during the Spring '10 term at École Normale Supérieure.

Ask a homework question - tutors are online