Presentation is loading. Please wait.

Presentation is loading. Please wait.

OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.

Similar presentations


Presentation on theme: "OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use."— Presentation transcript:

1 OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use arrays of objects parameters and arrays multidimensional arrays the ArrayList class additional techniques for managing strings 1

2 ARRAYS An array is an ordered list of values each of which has their own position within the array. Each value/variable has a numeric index or subscript to refer to a particular element in the array. 2 0 1 2 3 4 5 6 7 8 9 scores 79 87 94 82 67 98 87 81 74 91

3 ARRAYS For example, an array element can be assigned a value, printed, or used in a calculation : scores[2] = 89; scores[first] = scores[first] + 2; mean = (scores[0] + scores[1])/2; System.out.println ("Top = " + scores[5]); 3

4 ARRAYS An array of size N is indexed from zero to N-1 The following array of integers has a size of 10 and is indexed from 0 to 9 4 0 1 2 3 4 5 6 7 8 9 scores 79 87 94 82 67 98 87 81 74 91

5 ARRAYS When an array is declared, the name of the array is the address in memory of the first value in the array. For instance, an array of 9 integers (indexed 0-8) would be located in memory like this: 5 1 Location 23 90 40 60 70 75 80 90 scores 012345678012345678 View of Memory

6 ARRAYS An array stores multiple values of the same data type. So if an array of integers is declared, only integers may be stored in that array, no strings or characters. 6

7 ARRAY TYPES The type can be primitive types or objects. Primitive types include arrays of integers, doubles, chars, longints etc. Therefore, we can create an array of integers, or an array of characters, or an array of String objects, etc. 7

8 ARRAYS In Java, the array itself is an object. Therefore: – Any of the methods that can be used on an object can be used on an array. 8

9 DECLARING ARRAYS The scores array could be declared as follows: int[] scores = new int[10]; Note that the type of the array (int[]) does not specify its size, but the new operator reserves memory locations to store 10 integers indexed from 0 to 9. 9

10 ARRAYS The type of the variable scores is int[] (an array of integers) It is set to a newly instantiated array of 10 integers. Only integers may be stored in this array. If we declared an array of strings, only strings may be stored in that array. 10

11 DECLARING ARRAYS Some examples of array declarations: float[] prices = new float[500]; boolean[] flags; flags = new boolean[20]; char[] codes = new char[1750]; int[] intArray ; //allocates no memory 11

12 ARRAYS You cannot access an index of an array until it is instantiated. int[] grades;; // grades Array has no memory allotted grades[3] = 7; // ERROR - grades[3] does not yet exist 12

13 class Basic_Array { final static int LIMIT = 10; public static void main (String args[]) { int[] list = new int [LIMIT]; for(int index = 0; index < LIMIT; index++) list[index] = index * 10; list[5] = 999; for (int value : list) // forEach value in list System.out.print (value + " "); } // method main // stores increments of 10 in each element 13 Creates AND PRINTS an array with 10 elements

14 LIST 14 0 10 20 30 40 50 60 70 80 90 01234567890123456789 0 10 20 30 40 999 60 70 80 90 01234567890123456789 Element index 5 is change to 999, which is the 6th element in the array.

15 ARRAYS The constant LIMIT holds the size of the array. This is a good programming technique because it allows you to change the size of the array in one place - at the beginning of the program. The square brackets in the array declaration are an operator in Java. They have a precedence relative to other operators i.e. the highest precedence. Both constants in the previous example were declared static because only copy of the size of the array is needed. 15

16 BOUNDS CHECKING Each array object has a public constant called length that stores the size of the array. It is referenced through the array name (just like any other object): 16

17 LENGTH OF AN ARRAY scores.length; Length is a constant defined in the array class. scores. length holds the number of elements YOU allocated, not the largest index. 17

18 ARRAYS Arrays are considered to be a static structure because they have a fixed size. They cannot shrink or grow in size. 18

19 INITIALIZER LISTS An initializer list can be used to instantiate and initialize an array in one step. The values are delimited by braces and separated by commas. Examples: int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476}; char[] letter_grades = {'A', 'B', 'C',’D’};  The letter_grades array consists of an array of 4 characters. 19

20 INITIALIZER LISTS  Note that when an initializer list is used:  the new operator is not used  no size value is specified  The size of the array is determined by the number of items in the initializer list.  The array size is set to the number of elements in the initializer list. 20

21 OUTLINE 21 Declaring and Using Arrays Arrays of Objects Two-Dimensional Arrays Variable Length Parameter Lists The ArrayList Class

22 MULTIDIMENSIONAL ARRAYS A one-dimensional array stores a simple list of values. A two-dimensional array can be thought of as a table of values, with rows and columns. A two-dimensional array element is referenced using two index values. 22

23 TWO-DIMENSIONAL ARRAY To be precise, a two-dimensional array in Java is an array of arrays, therefore each row can have a different length. 23

24 TWO-DIMENSIONAL ARRAYS A one-dimensional array stores a list of elements A two-dimensional array can be thought of as a table of elements, with rows and columns 24 one dimension two dimensions

25 TWO-DIMENSIONAL ARRAYS A two-dimensional array is declared by specifying the size of each dimension separately: int[][] scores = new int[12][50]; A array element is referenced using two index values: value = scores[3][6] The array stored in one row can be specified using one index E.G. scores[2] is row 2 25

26 TWO-DIMENSIONAL ARRAYSExpressionTypeDescription tableint[][] 2D array of integers, or array of integer arrays table[5]int[] Single array of integers table[5][12]int A single integer 26

27 MULTIDIMENSIONAL ARRAYS int[][] table = { {28, 84, 47, 72}, {69, 26}, {91, 40, 28}, {42, 34, 37}, {13, 26, 57, 35} }; The first values - 28, 84, 47 and 72 represent the first row of the array. The second set of values are the 2nd row: 28 84 4772 69 26 91 40 28 42 34 37 13 26 5 35 27

28 TWO DIMENSIONAL ARRAYS In an initializer list, the first values represent the first element in the array. {28, 84, 47, 72} int[][] table = { {28, 84, 47, 72}, {69, 26}, {91, 40, 28}, {42, 34, 37}, {13, 26, 57, 35} }; {28, 84, 47, 72}, is row one 28

29 public class PassArrays { public static void main(String args[]) { int grades[][] = { { 100, 79, 83 }, { 44, 56, 67 }, { 95, 88, 99 } }; printStudentScores( grades[1] ); } // To print one row of the TwoD array public static void printStudentScores( int[] row ) { System.out.print("Scores for student: "); for (int i = 0; i < row.length; i++) System.out.println(row[i]); } 29

30 VARIABLE LENGTH PARAMETER LISTS Suppose we wanted to create a method that processes a different amount of data from one method call to the next For example, let's define a method called average that returns the average of a set of integer parameters 30 // one call to average three values mean1 = average (42, 69, 37); // another call to average seven values mean2 = average (35, 43, 93, 23, 40, 21, 75);

31 VARIABLE LENGTH PARAMETER LISTS We could define two versions of the average method Downside: we'd need a separate version of the method for each parameter count We could define the method to accept an array of integers Downside: we'd have to create the array and store the integers prior to calling the method each time Instead, Java provides a convenient way to create variable length parameter lists 31

32 VARIABLE LENGTH PARAMETER LISTS Using special syntax in the parameter list, we define a method to accept any number of parameters of the same type For each call, the parameters are automatically put into an array for easy processing in the method 32 public double average (int... list) { // whatever } element type array name Indicates a variable length parameter list

33 VARIABLE LENGTH PARAMETER LISTS 33 public double average (int... list) { double result = 0.0; if (list.length != 0) { int sum = 0; for (int num : list)// For Each Loop sum += num; result = (double)num / list.length; } return result; } // We need to use the for each loop

34 VARIABLE LENGTH PARAMETER LISTS The type of the parameter can be any primitive or object type. We can send any number of grades to the method below: 34 public void printGrades (Grade... grades) { for (Grade letterGrade : grades) System.out.println (letterGrade); } gradesGrade grades is the array, Grade is the type

35 VARIABLE LENGTH PARAMETER LISTS A method that accepts a variable number of parameters can also accept other parameters The following method accepts an int, a String object, and a variable number of double values into an array called nums 35 public void test (int count, String name, double... nums) { // whatever } The variable list parameter must be on the end of the parameter list.

36 THE ARRAYLIST CLASS An object of class ArrayList is similar to an array in that it stores multiple values However, a ArrayList only stores objects. only stores objects. can grow and shrink in size can grow and shrink in size Service methods provided by the ArrayList class are used to interact with a ArrayList.. 36

37 THE ARRAYLIST CLASS ArrayList is dynamic, that is, it is able to change its’ size as needed. A static structure like an array has a fixed size throughout its existence. Each ArrayList initially has a certain amount of memory space reserved for storing elements. 37

38 ARRAYLIST CLASS If an element is added that doesn't fit in the existing space, more room is automatically acquired. If more room is needed, a new, larger array is allocated and the old array is copied to it We will use this class later. 38

39 THE ARRAYLIST CLASS Elements can be inserted or removed by calling a method in the classs When an element is inserted, the other elements "move aside" to make room Likewise, when an element is removed, the list "collapses" to close the gap 39

40 ARRAYLISTS The major advantage of an ArrayList is: we can store different types of objects in it. The methods are designed to accept references to any type, so you can send a reference to a string, an integer, a double etc. can be passed. 40

41 PRIMITIVE DATA TYPES & ARRAYLIST HOWEVER, If you send a primitive data type, you must first change it to an object. E.g. You want to send the number 5 You create an Integer object first: Integer obj = new Integer(5); Double doublenum = new Double(2.98); 41

42 ARRAYLIST CLASS The benefit of storing objects are that different kinds of objects can be stored in the same data structure. Integers, Doubles, Floats You must inport the java.util package to use an ArrayList 42

43 43 add(Object element); adds element to end of list remove (Object element); removes the object from the ArrayList. The parameter is an alias to the object to be removed. contains (Object element); returns true if the object is in the ArrayList. get (int index) returns the object at the index specified. ensureCapacity() expands array by creating a new array and copying old one to the new one lastIndexOf(Object element) returns the last occurrence of element. size() returns the number of objects. … and many more The ArrayList class Service methods:

44 THE ARRAYLIST CLASS Object An ArrayList stores references related to the Object class, any kind of object So you can store any kind of object We can also define an ArrayList to accept a particular type of object 44

45 The following declaration creates an ArrayList object that only stores Family objects, not allowing other types of objects to included ArrayList reunion = new ArrayList ArrayList reunion = new ArrayList This is an example of generics introduced a few years ago. It is also the reason why I cannot get my DatingService applet to run on the browsers 45

46 STATIC VARIABLES Suppose we have a law firm that wants to keep count of the number of new clients added each. We would implement a Client class and put a counter in it so we could access anytime. The Client class has a getter method called Return count() 46

47 public class Client implements Comparable { private int count = 0; private String lastname, firstname, …… // constructor increments count when client created public Client(String lastname, String firstname, ….) { this.lastname = lastname; this.firstname = firstname; count++; } public int returnCount() { return count; } …. Other code 47

48 USING STATIC VARIABLES So we create a large number of clients during the day and then want to know the count. We create the last client of the day: Client c1 = new Client(“Harry”, “Hamlin” ….etc) And call the returncount method to find our total client count int count = c1.return count(); WHAT VALUE IS returned and stored in count? 48

49 STATIC VARIABLES One - yes - one! -because count is an instance variable in the Client class and each new client gets its own copy. It is only incremented once – when the client is created. When the next client is created, it had its own copy and it is only incremented once. LET MAKE COUNT STATIC! 49

50 public class Client implements Comparable { private static int count = 0; private String lastname, firstname, …… // constructor increments count when client created public Client(String lastname, String firstname, ….) { this.lastname = lastname; this.firstname = firstname; count++; } public int returnCount() { return count; } …. Other code 50

51 STATIC VARIABLES Now, the static count variable will be stored in memory when the first client is created ( of before) and there is just ONE count variable shared among all clients. there is just ONE count variable shared among all clients. it will return the total number of clients. When the returnCount method is called - it will return the total number of clients. 51

52 Declaring and using a TWO D array in Checker Project // first declare and instantiate an two-d array of squares Square[][] checkerboard = new Square[MAX_SIZE][MAX_SIZE]; int row, col, x =0, y =0 ; //In the init method, fill the array of squares: // Now create all the squares and draw them: { // code to create a two D array of squares // use a condition that will alternates between red and black squares // and then create a new square checkerboard[row][col] = new Square(x, y…… parameters); // now draw each square calling the draw method in the square class } 52

53 CON’D else //Draws other color squares { checkerboard[row][col] = new Square(constructor parameters); // now draw the square calling the drawmethod in //the square class } // close else } //close inner for } // close outer for // The code is not complete - you have to change the x //and y values as you cross the rows // and when you move to the next row, change x and y values again 53


Download ppt "OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use."

Similar presentations


Ads by Google