Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Arrays Work with Arrays, one and two dimensional to make processing multiple occurrences of similar data elements more efficient Also learn simple sorting and searching 1 Handouts and Sources: UsingArrays.java Java application using arrays Java.util.Arrays we take a brief look at this class 2 INTRO: We use arrays to hold many instances of a repetitive data structure. We can also use arrays with loops and also learn how to sort and search arrays. Arrays are a central aspect of almost any application. In this Lecture, we will learn how to declare, populate, modify, sort and process arrays. 3 INTRO: We will also pass arrays as arguments to methods. In the next lecture, Algorithms, we will further explore arrays by applying other sort and search algorithms against them. We will also look at Java’s Array Class ( java.util.arrays ) and examine the classes sorting (and other) methods. 4 About Arrays: In many cases you will need to process many instances of information that share a common data type (primitive or a class/object) 5 About Arrays: That common type can be a primitive data type such as an integer or a double BUT it can also be an array of Strings (Java class) 6 About Arrays: However, the common data type can be an instance of a class, like the Number class (we will be discussing the data type class Number right after the Algorithm lecture) 7 About Arrays: When dealing with an array of a “class” we can make excellent use of Java’s polymorphic ability 8 About Arrays: We can create a generic type of array that contains “some type of Number class” for example and then populate each element of that array with a DIFFERENT TYPE of the Number class, like Integer or Double 9 About Arrays: We will see an example of this in this lecture so you can begin to start thinking about this concept, but we will get much more into this type of array in upcoming lectures. 10 An array occupies N occurrences of a specified amount of memory assigned to a specific primitive data type or object under ONE VARIABLE NAME int myInt[] = {5,3,45,67,12,81,97, 109, 11, 6}; 11 The variable myInt refers to several occurances, in memory, that will hold an integer value The actual memory block assigned is called the array The individual integer’s in this array is called the element of the array 12 The size or length of the array refers to the number of elements in the array You can access an element of the array by using the elements index or subscript System.out.println( myInt[5] ); // prints out 81 13 Int sub = 5; System.out.println( myInt[sub] ); // prints out 81 Remember that Array Indices START at ZERO, so the 7th element of the array has an index of 6 14 Without arrays, we would have to create numerous variables, each with a different name, to process the same information. In that case we would not be able to make use of repetitive processing (loops) 15 1-D Arrays: Declaring arrays: int scores[ ], scores2[ ] ; int [ ] scores, scores2; String b[ ] = new String[100] ; x[ ] = new String[25]; 16 Arrays are treated AS OBJECTS !!! After you declare a placeholder for your array, you need to create / instantiate it into memory by using the new operator int scores[ ]= new int[10]; // combines declaration and //instantiation in one step 17 // declare and allocate in 2 steps int c[ ]; c = new int[10]; int myInt[ ] = {5,3,45,67,12,81,97, 109, 11, 6}; // this also instantiates "new” This is an example of an initializer list 18 TPS Create arrays of ints and strings using the different instantiation methods (use new, check default states, use initializer list) Set values using loops and display certain elements of the array. 19 When an array is created, its elements are initialized to default values: Numeric primitives are set to ZERO Booleans are set to FALSE Class types means that the array actually contains REFERENCES to objects of that type (String for example) and the array elements are initialized to null 20 WHEN dealing with an array of objects (class references) YOU must initialize EACH element before it is used by setting it to a valid reference // Color class in the java.awt.Color // API Color colors[ ] = new Color[16]; colors[0] = new Color(207, 189, 250); colors[1] = Color.blue; 21 Both do the same thing, in the second, the new is implied Now, the first 2 elements in the color array have valid references and you will not get a null object Reference error If you explicitly define the values in an object array’s declaration, then you do not need to initialize each element with new 22 String names[] = {"Giants","Chiefs", "Mets"}; This creates 3 element array of Strings Color rainbowColors[ ] = { Color.red, Color.yellow, Color.green, Color.cyan, Color.blue, Color.magenta }; 23 NOTE: You may have seen this object when we worked with graphics (awt, swing, etc…) Once you declare and initialize an array, YOU can not change its size You can only copy the array into a larger array and then destroy the old one 24 TPS Create an array of the color, string or any other object and try to work with an array element that is not initialized 25 Length: Every Array KNOWS its own size (length) You can access the length of an array by using the expression Arrayvar.length This returns the integer length of the array length acts as a public field that holds the size of the array int l = colors.length; // returns 16 26 TPS: write pseudo code for how we could copy one array into a LARGER array (make sure to use the length method) 27 ONE (SLEEK) ANSWER IS: // increase array size int x[] = new int[c.length * 2]; System.arraycopy(c, 0 , x, 0 , c.length); c = x; // reset orig with larger array Use a constant to set the size of an array final int ARRAY_SIZE = 10; c = new int[ARRAY_SIZE]; 28 Accessing Array Elements: Use an Index (subscript) to access individual elements of the array Remember that indices start at ZERO // import java.util.Random final int ARRAY_SIZE = 10; c = new int[ARRAY_SIZE]; 29 Random myRand = new Random(); int rN = 0; for (int s = 0; s < c.length; s++) { rN = myRand.nextInt(); c[s] = rN; } This loop sets each element (0 thru 9 index) to random integers You can also use expressions in the index c[s * 2]; 30 ALL indices, however, must fall in the range from ZERO to length – 1 If you try to access an element outside the range of the array you will get an exception error IndexOutOfBoundsException Arrays, unlike Strings, are NOT immutable as you can assign and reassign the values in an array’s elements 31 TRY OUT THE FOR EACH LOOP: // FOR EACH LOOP // USE the FOR EACH approach to iterate //over each element in the // generic Number Array System.out.println(" TRYING OUT FOR EACH LOOP..."); for(Number v : nums) { System.out.println(v.toString()); } 32 TPS Create an array of random numbers, then increase the array using the “arraycopy” method Purposely get an array out of bounds error 33 Passing Arrays to and Returning Arrays from Methods: In C++, you can pass arguments to methods either BY REFERENCE or BY VALUE Passing by reference allows the called method to make changes to the passed variable Passing by value actually passes a COPY of the variable so any changes to the by value argument are NOT reflected in the calling method or function 34 In JAVA, the programmer has no choice in HOW an argument will be passed Primitive data types will ALWAYS be passed as a COPY (by value) Objects will ALWAYS have their ADDRESSES or REFRENCES passed 35 These references are also passed BY VALUE, however, since the objects memory location is passed any changes made to that objects STATE are reflected in the actual instance variable Just like any primitive or object, arrays can be passed to methods (or static functions) Just like any primitive or object, arrays can be returned from methods (or static functions) 36 TPS Create an array in SPVM, print the first value of the array Then write a function that takes an array as an argument, modify the first element of the passed array In SPVM, after the function is called, print out the first element and see how the change made in the function is reflected in the array local to SPVM Do the same with an integer and see how the change made in the function is NOT reflected 37 In reality, when you pass an array to a method or have an array returned from a method, ONLY THE REFERENCE TO (address of in memory) the beginning of the array (contiguous block of memory) is passed. Most Java documentation states that arrays are passed to methods as references. The method receiving the array actually receives the address of the original array and works with the ARRAY located at that memory location (remember that arrays of any type are 38 treated as objects by Java) Example: // change array passed "by reference" System.out.println("array x's first element BEFORE call: " + x[0]); changeArray(x); System.out.println("array x's first element AFTER call: " + x[0]); 39 static void changeArray(int a[]) { a[0] = 999; } 40 THEREFORE any CHANGE made to the array in the called method is actually modifying the original array because it has access to its ACTUAL location in memory Here is the output of the call to changeArray Array x BEFORE call -91 Array x AFTER call 999 41 static void changeArray (int a[ ]) Prototype of the static method states that it will pass an array by stating (int a[ ] ) you only need the empty brackets because Java is smart enough to understand you are passing an array and since only the REFERENCE to the beginning of the array is passed, it does not need to know the SIZE of the array 42 static int[ ] tells Java that this method will RETURN an integer array. Again no size is required as only the reference to the array is returned changeArray(x); calls the methods and passes an integer array Also receives the returned array. x is an int array and Java knows that changeArray is passed an integer array, so you do not need brackets here 43 return c; Returns a reference to an array back to whoever issued the method call to junkArea (SPVM) 44 NOTE: As we will learn in an upcoming lecture on Java and Memory management, ALL parameters / arguments are actually passed BY VALUE, even the references to objects are passed by value. The question arises that, if everything is passed by VALUE, then how can any changes made to an argument in the called program affect the calling program (original source of the variable) ? 45 The answer is that, primitive data types are truly passed by VALUE , automatically, and because primitives contain actual values and not REFERENCES to a place in memory where the actual value resides (like objects) a COPY is passed to the called program. 46 This COPY becomes, in essence, a LOCAL variable in the called method. Once the method goes out of scope (a return is issued) that copy is flushed from memory. 47 Hence, any changes made to the COPY are NOT reflected in the original variable (primitive). With objects, they too are actually passed by VALUE. However with objects, the actual reference (address of in memory) to the object is passed. 48 Because the called method has access to the original object any changes made are made to the original object’s state. This is true because unlike a local variable, the reference to the object is not destroyed when the method goes out of scope (unless specifically set to null in the called method) so the change made stays resident in the original object. 49 In short, in Java ALL objects are references and can only be passed by their address or reference WHILE ALL primitive data types are values and can only be passed as a copy (GIVE AN ILLUSTRATION ON BOARD OF OBJECT AND PRIMITIVE BEING PASSED, MODIFIED AND RETURNED) 50 Passing 1 Element of an Array: When you pass the “entire array” to a method, changes made to the array are maintained However, if you pass only 1 element of an array then, depending on the data type of the array, that element will either be passed as a COPY or as a REFERENCE COPY If the array is of a primitive data type the argument is passed as a COPY ONLY 51 If the array is an object the argument’s REFERENCE is passed Example of a primitive data type: System.out.println("c[2] before call is " + c[2]); junkArea2(c[2]); System.out.println("c[2] after call is " + c[2]); 52 static void junkArea2(int a) { a += 21; return; } Output: c[2] before call is 11 c[2] after call is 11 Note that the element in the original array remained UNCHANGED 53 Example of a MUTABLE object (String is immutable so the change would NOT Be reflected in the original array!!!) StringBuffer names[] = new StringBuffer[3];//{"Giants","Chiefs", "Mets"}; names[0] = new StringBuffer("Giants"); names[1] = new StringBuffer("Chiefs"); names[2] = new StringBuffer("Mets); 54 System.out.println("names[0] before call is " + names[0]); junkArea2(names[0]); System.out.println("names[0] after call is " + names[0]); static void junkArea2(StringBuffer a) { a.append(" RULE !!!"); return; } 55 Output: names[0] before call is Giants names[0] after call is Giants RULE !!! Note that the original array element of StringBuffer objects, which are mutable, WAS modified in the original array 56 TPS Try passing an ARRAY reference to a method Try passing an array element to a method Identify the difference Set up a function that accepts an array of strings. Set the first element to null and 57 try to access it in SPVM TPS ANSWER String s2[] = new String[5]; s2[0] = "nelly"; System.out.println("String Array BEFORE call: " + s2[0].length()); nullifyString(s2); System.out.println("String Array AFTER call: " + s2[0].length()); 58 TPS ANSWER static void nullifyString(String s[]) { s[0] = null; } 59 TPS ANSWER String Array BEFORE call: 5 Exception in thread "main" java.lang.NullPointerException at UsingArrays.main(UsingArrays.java:70) 60 Method Overloading Important to note that there are 2 functions called junkArea2 How is this possible? Because of the concept of function / method overloading (EXPLAIN) 61 TPS: Take the junkArea code and run it. Then make changes and see what happens (errors) 62 2-D Arrays: 2-D arrays are typically used to represent rectangular tables that contain similar elements (same primitive data type OR an object that is a super object that may contain different inherited versions by way of subclasses) Examples of uses for 2-D arrays are game boards (chess, checkers, tic-tac-toe) spreadsheets, matrix or picture image broken down into pixels 63 // 2d array int rows = 2, cols = 3; String s1[][] = new String[rows][cols]; // an array or // matrix of 2 rows by 3 columns, init // to null double a1[][] = { {0.0, 0.1,0.2}, {1.0, 1.1, 1.2} }; 64 // access 2d array System.out.print("First Row[R][C] (cols 0,1,2)" + a1[0][0] + " "+ a1[0][1] + " ” + a1[0][2] + "\n"); System.out.print("First Row[R][C] (cols 0,1,2)" + a1[1][0] + " "+ a1[1][1] + " ” + a1[1][2] + "\n"); OUTPUT IS: First Row[R][C] (cols 0,1,2)0.0 0.1 0.2 First Row[R][C] (cols 0,1,2)1.0 1.1 1.2 65 Be careful when attempting to get the LENGTH of a 2-D array The length method will return either the number of rows in an array or the number of columns in the array It all depends on how you call the length method 66 Example: System.out.println("Number of ROWS in Array " + a1.length); System.out.println("Number of COLS in 1st Row of Array " + a1[0].length); OUTPUT IS: Number of ROWS in Array 2 Number of COLS in 1st Row of Array 3 67 NOTE: 2-D arrays may have ROWS that each have a DIFFERENT number of COLUMNS This is a ragged array which we do not explicitly cover in this course 68 TPS: How do you process, iterate over, every element of a 2-D array ? 69 TPS Create a 2D array, initialize it and then print out the array’s elements using a NESTED FOR LOOP 70 Sorting Arrays: In the next lecture, Algorithms, we will learn the Selection Sort, Insertion Sort and Binary Search For now, we will introduce a simple Sort algorithm, the Bubble Sort It is critical to be able to sort an array in some order (ascending, descending) so that you can apply an efficient SEARCH algorithm against it 71 Suppose we have an array of 1 million names If we did not have those names sorted, any search against that array, for a specific name, would have to be performed sequentially That is the an inefficient sort --- linear or O(n) 72 Bubble Sort: With this type of sort the higher or lower (depending on asc or desc sort) numbers gradually bubble their way to the top of the array (element ZERO) Several passes are made through the array 73 Bubble Sort: With each pass, successive pairs of elements are compared For if the values are out of order, they are swapped with each other The total number of comparisons is (n-1)n/2 74 Bubble Sort: This is an O(n^2) sort Quadratic Time and a Polynomial Sort 75 TPS: Create 2 arrays, integer and string Create 2 overloaded sort functions Perform a sort and print out elements to verify 76 for (c1 = 0; c1 < (v.length - 1); c1++) { for (c2 = (c1 +1); c2 < v.length; c2++) { if (v[c1] > v[c2]) { temp = v[c1]; v[c1] = v[c2]; v[c2] = temp; } 77 Array Class (java.util.Arrays): This class implements binary searches, sorts These methods are static To use this class, you must: Import java.util.Arrays 78 To sort an array using this class, you call the Arrays.sort method This method can sort arrays of simple data types plus arrays of Strings The sort algorithm applied is a version of the MergeSort algorithm 79 // SORT c Arrays.sort(c); // ascending order System.out.println("AFTER SORT values... " ); for(int d = 0; d < c.length; d++) { System.out.println("c[" + d + "] is " + c[d]); } 80 NOTE: You can also specify a range to sort on by using overloaded sort methods Notice we do not instantiate Arrays class because it is a static class 81 AFTER SORT values... c[0] is -50 c[1] is -45 c[2] is -36 c[3] is 5 c[4] is 16 c[5] is 30 c[6] is 43 c[7] is 46 c[8] is 77 c[9] is 94 82 Arrays of objects: You can create an array of a developer defined class Assume that there is a class written called Student Also assume that one of the methods of this class is a getAverage method 83 The process you follow is just like the process for other objects like StringBuffer NOTE: passing single elements of an array may be VALUE or REFERENCE depending on their mutability If the class has modifier methods, then the changes made will be reflected in the original array 84 Example: Student[ ] studentArray = new Student[10]; For ( …..) StudentArray[x] = new Student(constructor arguments) Sum student averages… 85 Example: For ( …..) Sum += studentArray[x].getAverage(); 86 System Time (useful for projects): Following code taken from vectortoarray.java in TAFT wkshp 2002 folder: private long start=0, end=0; start = System.currentTimeMillis(); end = System.currentTimeMillis(); 87 Lets review the sample code: UsingArrays.java 88 Projects: Sum Array Student Grades Sort Comparison Reverse an Array Tic Tac Toe Nim Spell Checker 89 TEST IS THE DAY AFTER THE PROJECT IS DUE !!! 90