Objects for Organizing Data --

53
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

description

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. - PowerPoint PPT Presentation

Transcript of Objects for Organizing Data --

Page 1: Objects for Organizing Data  --

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

Page 2: Objects for Organizing Data  --

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

Page 3: Objects for Organizing Data  --

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

Page 4: Objects for Organizing Data  --

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

Page 5: Objects for Organizing Data  --

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 8090

scores

01 2 3 4 5 6 78

View of Memory

Page 6: Objects for Organizing Data  --

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

Page 7: Objects for Organizing Data  --

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

Page 8: Objects for Organizing Data  --

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

Page 9: Objects for Organizing Data  --

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

Page 10: Objects for Organizing Data  --

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

Page 11: Objects for Organizing Data  --

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

Page 12: Objects for Organizing Data  --

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

Page 13: Objects for Organizing Data  --

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

Page 14: Objects for Organizing Data  --

LIST

14

0 10 20 30 40 50 60 70 80 90

01 2 3 4 5 6 7 89

0 10 20 30 40 999 60 70 80 90

01 2 3 4 5 6 7 89

Element index 5 is change to 999, which is the 6th element in the array.

Page 15: Objects for Organizing Data  --

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

Page 16: Objects for Organizing Data  --

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

Page 17: Objects for Organizing Data  --

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

Page 18: Objects for Organizing Data  --

ARRAYS

• Arrays are considered to be a static structure because they have a fixed size.

• They cannot shrink or grow in size.

18

Page 19: Objects for Organizing Data  --

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

Page 20: Objects for Organizing Data  --

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

Page 21: Objects for Organizing Data  --

OUTLINE

21

Declaring and Using Arrays

Arrays of Objects

Two-Dimensional Arrays

Variable Length Parameter Lists

The ArrayList Class

Page 22: Objects for Organizing Data  --

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

Page 23: Objects for Organizing Data  --

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

Page 24: Objects for Organizing Data  --

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

Page 25: Objects for Organizing Data  --

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 225

Page 26: Objects for Organizing Data  --

TWO-DIMENSIONAL ARRAYS

ExpressionExpression TypeType DescriptionDescription

tabletable int[][]int[][] 2D array of integers, or2D array of integers, or

array of integer arraysarray of integer arrays

table[5]table[5] int[]int[] Single array of integersSingle array of integers

table[5][12]table[5][12] intint A single integerA single integer

26

Page 27: Objects for Organizing Data  --

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

Page 28: Objects for Organizing Data  --

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

Page 29: Objects for Organizing Data  --

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

Page 30: Objects for Organizing Data  --

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 valuesmean1 = average (42, 69, 37);

// another call to average seven valuesmean2 = average (35, 43, 93, 23, 40, 21, 75);

Page 31: Objects for Organizing Data  --

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

Page 32: Objects for Organizing Data  --

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}

elementtype

arrayname

Indicates a variable length parameter list

Page 33: Objects for Organizing Data  --

VARIABLE LENGTH PARAMETER LISTS

33

public double average (int ... list){ double result = 0.0;

if (list.length != 0) { int sum = 0;

for (int num : listfor (int num : list)// )// For Each LoopFor Each Loop sum += num; result = (double)num / list.length; }

return result;} // We need to use the for each loop

Page 34: Objects for Organizing Data  --

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);}

gradesgrades is the array, GradeGrade is the type

Page 35: Objects for Organizing Data  --

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.

Page 36: Objects for Organizing Data  --

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 sizecan grow and shrink in size

• Service methods provided by the ArrayList

class are used to interact with a ArrayList.. 36

Page 37: Objects for Organizing Data  --

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

Page 38: Objects for Organizing Data  --

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

Page 39: Objects for Organizing Data  --

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

Page 40: Objects for Organizing Data  --

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

Page 41: Objects for Organizing Data  --

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

Page 42: Objects for Organizing Data  --

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

Page 43: Objects for Organizing Data  --

43

add(Object elementadd(Object element); ); adds element to end of list adds element to end of list

remove (Object elementremove (Object element); removes the object from the ArrayList. The ); removes the object from the ArrayList. The parameter is an alias to the object to be removed. parameter is an alias to the object to be removed.

ccontains (Object element);ontains (Object element); returns true if the object is in the ArrayList.returns true if the object is in the ArrayList.

get (int index)get (int index) returns the object at the index specified. returns the object at the index specified.

ensureCapacityensureCapacity()() expands array by creating a new array and copying expands array by creating a new array and copying old one to the new oneold one to the new one

lastIndexOf(Object element)lastIndexOf(Object element) returns the last occurrence of element.returns the last occurrence of element.

size()size() returns the number of objects. returns the number of objects. … and many more… and many more

The ArrayList class Service methodsThe ArrayList class Service methods::

Page 44: Objects for Organizing Data  --

THE ARRAYLIST CLASS• An ArrayList stores references related to the ObjectObject class,

• So you can store any kind of objectany kind of object

• We can also define an ArrayList to accept a particular type of object

44

Page 45: Objects for Organizing Data  --

• The following declaration creates an ArrayList object that only stores Family objects, not allowing other types of objects to included

ArrayList ArrayList <<FamilyFamily> reunion = new > reunion = new ArrayList ArrayList <<FamilyFamily>>

• 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

Page 46: Objects for Organizing Data  --

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

Page 47: Objects for Organizing Data  --

• public class Client implements Comparable<Client>{ 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

Page 48: Objects for Organizing Data  --

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

Page 49: Objects for Organizing Data  --

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

Page 50: Objects for Organizing Data  --

• public class Client implements Comparable<Client>{ 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

Page 51: Objects for Organizing Data  --

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 there is just ONE count variable shared among all clients.among all clients.

• When the returnCount method is called - it will return the total number of clients.it will return the total number of clients.

51

Page 52: Objects for Organizing Data  --

• 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

Page 53: Objects for Organizing Data  --

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