Objects for Organizing Data --

85
1 Objects for Organizing Data Objects for Organizing Data -- -- As our programs get more sophisticated, we As our programs get more sophisticated, we need assistance organizing large amounts of need assistance organizing large amounts of data. Chapter 6 focuses on: data. Chapter 6 focuses on: array declaration and use array declaration and use arrays of objects arrays of objects parameters and arrays parameters and arrays multidimensional arrays multidimensional arrays the the ArrayList ArrayList class class additional techniques for managing strings additional techniques for managing strings

description

Objects for Organizing Data --. As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array declaration and use arrays of objects parameters and arrays multidimensional arrays the ArrayList class - PowerPoint PPT Presentation

Transcript of Objects for Organizing Data --

1

Objects for Organizing Data --Objects for Organizing Data --

As our programs get more sophisticated, we need assistance As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on:organizing large amounts of data. Chapter 6 focuses on:

• array declaration and usearray declaration and use

• arrays of objectsarrays of objects

• parameters and arraysparameters and arrays

• multidimensional arraysmultidimensional arrays

• the the ArrayListArrayList classclass

• additional techniques for managing stringsadditional techniques for managing strings

Chap6 2

Static Variables - DetailsStatic Variables - Details

Normally, each object has its own data space.Normally, each object has its own data space.

If a variable is declared as static, only one copy of the If a variable is declared as static, only one copy of the variable exists for all objects of the classvariable exists for all objects of the class

private static int count;private static int count;

Changing the value of a static variable in one object Changing the value of a static variable in one object changes it for all others.changes it for all others.

Static variables are sometimes called Static variables are sometimes called class variables.class variables.

3

Unless otherwise specified, a member declared within a Unless otherwise specified, a member declared within a class is an instance variable. In the following Numbers class is an instance variable. In the following Numbers class, there are class, there are

Two instance variables,Two instance variables,

• an integer - num1 an integer - num1

• an integer - count an integer - count

• plus one accessor method - plus one accessor method - ReturnNum().ReturnNum().

The static ModifierThe static Modifier

4

Class NumbersClass Numbers In this version , there are two instance variables.In this version , there are two instance variables.

class Numberclass Number

{ { private int count = 0 ;private int count = 0 ; private int num1; private int num1;

public Number(int value)public Number(int value) { // constructor { // constructor num1 = value;num1 = value;

count ++; } count ++; }

public int returnNum()public int returnNum() { // service method { // service method return num1; return num1; } }

5

Static VariablesStatic Variables

Each object that it is created in the Numbers class Each object that it is created in the Numbers class contains a: contains a:

• copy of the num1copy of the num1 and count variables and count variables

• and has access to the ReturnNum method.and has access to the ReturnNum method.

Each object has unique values for the num1 instance Each object has unique values for the num1 instance

variable and count.variable and count.

6

Class NumbersClass NumbersIn the main method of the Driver class, class TestIn the main method of the Driver class, class Test

class Testclass Test

{{

public static void main(String args[])public static void main(String args[])

{{

Number Number num1num1 = new Number(17); = new Number(17);

Number Number num2num2 = new Number(12); = new Number(12);

}}

In memory,In memory, number number has has

a copy of a copy of num1 and countnum1 and count

Number 58

Number 2 60

58 num1 17

count 1

60 num2 12

count 1

7

When declaring a static variable or method, When declaring a static variable or method, only oneonly one copy of the copy of the variable or method is created. All instances of the class share the same variable or method is created. All instances of the class share the same copy. copy.

class Numberclass Number { { staticstatic int count = 0; int count = 0; // one copy for all instances// one copy for all instances

private int num1;private int num1;

public Number(int value)public Number(int value) { { count++; count++;

num1 = value ; num1 = value ;

} }

public int returnNum()public int returnNum() { { return num1; return num1; }}

}}

Static Variables

8

Class NumbersClass Numbersclass Testclass Test

{{

public static void main(String args[])public static void main(String args[])

{{

Number Number num1num1 = new Number(17); = new Number(17);

NumberNumber num2num2 = new Number(20);= new Number(20);

}}

In memory,In memory, number1 and number1 and

Number2, Number2, and two copies of and two copies of num1 are storednum1 are stored

but there is one copy of count but there is one copy of count

for the classfor the class

num1 57

num2 60

57 num1 17

60 num1 20

62 count 2

9

Static VariablesStatic Variables

Memory space for a static variable is created when the Memory space for a static variable is created when the class is first referencedclass is first referenced

All objects instantiated from the class share its static All objects instantiated from the class share its static variablesvariables

Changing the value of a static variable in one object Changing the value of a static variable in one object changes it for all otherschanges it for all others

10

Static VariablesStatic Variables

When used properly, static variables are very effective. When used properly, static variables are very effective.

There is only one copy of the static variables named in a There is only one copy of the static variables named in a class.class.

This means that all the objects created from that class do This means that all the objects created from that class do not receive a copy of the static variables. not receive a copy of the static variables.

They just have access to their valueThey just have access to their value

11

Class StudentClass Studentclass Student {class Student {

private static int count = 0private static int count = 0; // a static variable; // a static variable

private int SocSecNum;private int SocSecNum;

private String name;private String name;

public Student () {public Student () { //CONSTRUCTOR//CONSTRUCTOR

count = count + 1;count = count + 1;

} // constructor Student} // constructor Student

public int ReturnCount() {public int ReturnCount() {

return count;return count;

} // method ReturnCount} // method ReturnCount

12

Every time you instantiate a new object from a class, you Every time you instantiate a new object from a class, you get a new copy of each of the class’s instance variables. get a new copy of each of the class’s instance variables.

With every new Student object, you get a newWith every new Student object, you get a new name name variable associated with the new Student object.variable associated with the new Student object.

All instances of the same class share the same All instances of the same class share the same implementation of the implementation of the ReturnCount method. ReturnCount method.

Objects outside the Student class can only access the static Objects outside the Student class can only access the static variable variable count count through the ReturnCount method.through the ReturnCount method.

Instance Variable and Methods

Chap6 13

The static ModifierThe static Modifier TheThe static static modifiermodifier can be applied to variables or can be applied to variables or

methods.methods.

It associates a variable or method with the class rather It associates a variable or method with the class rather than an object.than an object.

This approach is a distinct departure from the normal This approach is a distinct departure from the normal way of thinking about objects.way of thinking about objects.

We have already seen the static modifier used with We have already seen the static modifier used with variables. It can also be used with methods.variables. It can also be used with methods.

14

Static MethodsStatic Methods

Static methodsStatic methods are invoked using the class name are invoked using the class name and are and are sometimes called sometimes called class methodsclass methods..

Sometimes it is convenient to have methods that can be Sometimes it is convenient to have methods that can be used without creating an object. used without creating an object.

For instance, every time you want to use the factorial For instance, every time you want to use the factorial method or the method that we used to uppercase a method or the method that we used to uppercase a character you don’t want to create an instance of the character you don’t want to create an instance of the class.class.

15

The static ModifierThe static Modifier So, you create static methods. To invoke these methods, you simply So, you create static methods. To invoke these methods, you simply

use the class name, where you would otherwise use the object name. use the class name, where you would otherwise use the object name. E.g.;E.g.;

For example, theFor example, the Math Math class and the Character classes in theclass and the Character classes in the java.lang.java.lang.package contains several static method operations:package contains several static method operations:

Math.abs (num)Math.abs (num) // absolute value// absolute value

Character.toUppercase (c)Character.toUppercase (c) // uppercases a char// uppercases a char

y = Math.sqrt.(x) y = Math.sqrt.(x)

We used the methods in the character class without instantiating an We used the methods in the character class without instantiating an instance of the class.instance of the class.

Chap6 16

Static MethodsStatic Methods

Normally, we invoke a method through an instance Normally, we invoke a method through an instance (an object) of a class. (an object) of a class.

If a method is declared as static, it can be invoked If a method is declared as static, it can be invoked through the class name; no object needs to exist.through the class name; no object needs to exist.

17

Static MethodsStatic Methods

class Helper{ public static int cube (int num) { return num * num * num; }}

Because it is declared as static, the methodcan be invoked as

value = Helper.cube(5);

18

Static Class MembersStatic Class Members

Static methods and static variables often work togetherStatic methods and static variables often work together

The following example keeps track of how many The following example keeps track of how many SloganSlogan objects have been created using a static variable, and makes objects have been created using a static variable, and makes that information available using a static methodthat information available using a static method

See See SloganCounter.javaSloganCounter.java (page 294) (page 294)

See See Slogan.javaSlogan.java (page 295) (page 295)

19

ArraysArrays

An An arrayarray is an ordered list of values each of which has is an ordered list of values each of which has their own position within the array. their own position within the array.

It is a collection of variables that share the same name.It is a collection of variables that share the same name.

Each value/variable has a numeric Each value/variable has a numeric index or subscript index or subscript to to refer to a particular element in the array. refer to a particular element in the array.

0 1 2 3 4 5 6 7 8 9

scores 79 87 94 82 67 98 87 81 74 91

20

ArraysArrays

For example, an array element can be assigned a value, For example, an array element can be assigned a value, printed, or used in a calculationprinted, or used in a calculation::

scores[2] = 89;scores[2] = 89;

scores[first] = scores[first] + 2;scores[first] = scores[first] + 2;

mean = (scores[0] + scores[1])/2;mean = (scores[0] + scores[1])/2;

System.out.println ("Top = " + scores[5]);System.out.println ("Top = " + scores[5]);

21

ArraysArrays

An array of size An array of size N is indexed from zero to N-1N is indexed from zero to N-1

The following array of integers has a size of 10 and is The following array of integers has a size of 10 and is indexed from 0 to 9indexed from 0 to 9

0 1 2 3 4 5 6 7 8 9

scores 79 87 94 82 67 98 87 81 74 91

22

ArraysArrays

A particular value is referenced using the array name A particular value is referenced using the array name followed by the index in brackets For example, the followed by the index in brackets For example, the expression:expression:

scores[4];scores[4];

refers to the value 67 (which is the 5th value in the array).refers to the value 67 (which is the 5th value in the array).

Scores[0]Scores[0] is first element in the array - all indexes start at 0. is first element in the array - all indexes start at 0. The value stored in the 3rd index is the 4th element.The value stored in the 3rd index is the 4th element.

Scores[4]Scores[4] is a place to store a single integer, and can be is a place to store a single integer, and can be used wherever an integer variable can. For example, it can used wherever an integer variable can. For example, it can be assigned a value, printed, used in a calculation.be assigned a value, printed, used in a calculation.

23

ARRAYSARRAYS

When an array is declared, the name of the array is the When an array is declared, the name of the array is the address in memory of the first value in the array. For address in memory of the first value in the array. For instance, an array of 9 integers (indexed 0-8) called instance, an array of 9 integers (indexed 0-8) called intArrayintArray would be located in memory like this: would be located in memory like this:

1 Location 23 90

40 60 70 75 8090

scores

01 2 3 4 5 6 78

View of Memory

24

ArraysArrays

An array stores multiple values of the same data type. An array stores multiple values of the same data type.

So if an array of integers is declared, only integers may be So if an array of integers is declared, only integers may be stored in that array, no strings or characters.stored in that array, no strings or characters.

The type can be primitive types or objects. The type can be primitive types or objects.

Primitive types include arrays of integers, doubles, chars, Primitive types include arrays of integers, doubles, chars, longints etc. longints etc.

Therefore, we can create an array of integers, or an array of Therefore, we can create an array of integers, or an array of characters, or an array of String objects, etc. characters, or an array of String objects, etc.

25

ArraysArrays

In Java, the array itself is an object. Therefore:In Java, the array itself is an object. Therefore:

– Any of the methods that can be used on an object can Any of the methods that can be used on an object can be used on an array. be used on an array.

– The name of the array is a reference variable, and the The name of the array is a reference variable, and the array itself is instantiated separatelyarray itself is instantiated separately..

26

ArraysArrays

The chess object The chess object BishopBishop points to the place in memory points to the place in memory where all the variables and methods associated with the where all the variables and methods associated with the Bishop object are located,Bishop object are located,

So the name of the array points to the place in memory So the name of the array points to the place in memory where the individual values of the array are stored.where the individual values of the array are stored.

27

Declaring ArraysDeclaring Arrays

Since arrays are objects, the reference must first be declared Since arrays are objects, the reference must first be declared and then the array can be instantiated. and then the array can be instantiated.

The The scoresscores array could be declared as follows: array could be declared as follows:

int[] scores = new int[10];int[] scores = new int[10];

Note that the type of the array (Note that the type of the array (int[])int[]) does not specify its does not specify its size, but the new operator reserves memory locations to store size, but the new operator reserves memory locations to store 10 integers indexed from 0 to 9.10 integers indexed from 0 to 9.

28

ArraysArrays

The type of the variable The type of the variable scoresscores is is int[]int[] ( (an array ofan array of integersintegers) )

It is set to a newly instantiated array of 10 integers. Only It is set to a newly instantiated array of 10 integers. Only integers may be stored in this array. integers may be stored in this array.

If we declared an array of strings, only strings may be stored If we declared an array of strings, only strings may be stored in that array.in that array.

29

Declaring ArraysDeclaring Arrays Some examples of array declarations:Some examples of array declarations:

float[] prices = new float[500];float[] prices = new float[500];

boolean[] flags;boolean[] flags;

flags = new boolean[20];flags = new boolean[20];

char[] codes = new char[1750];char[] codes = new char[1750];

int[] intArray ; //allocates no memory int[] intArray ; //allocates no memory

30

ArraysArrays

You cannot access an index of an array until it is instantiated. You cannot access an index of an array until it is instantiated.

int[] grades;int[] grades; // grades Array has no memory allotted// grades Array has no memory allotted

grades[3] = 7grades[3] = 7; ; // ERROR - grades[3] does not yet exist// ERROR - grades[3] does not yet exist

31

class Basic_Arrayclass Basic_Array { {

final static int LIMIT = 10; final static int LIMIT = 10; // // value will not changevalue will not change as as final static int INCREMENT = 10; final static int INCREMENT = 10; // only one copy needed// only one copy needed

public static void main (String args[]){ public static void main (String args[]){ int[]list = new int[LIMIT];int[]list = new int[LIMIT];for(int index = 0; index < LIMIT; index++) for(int index = 0; index < LIMIT; index++)

list[index] = index * INCREMENT;list[index] = index * INCREMENT;

list[5] = 999;list[5] = 999;

for (int value : list) for (int value : list) // forEach value in list// forEach value in list

System.out.print (value + " ");System.out.print (value + " ");

} // method } // method main main // stores increments of 10 in each element// stores increments of 10 in each element

Creates an array with 10 elements

32

0 10 20 30 40 50 60 70 80 90

01 2 3 4 5 6 7 89

LIST LIST 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.

33

ArraysArrays

The constant The constant LIMIT LIMIT holds the size of the array. This is a holds the size of the array. This is a good programming technique because it allows you to good programming technique because it allows you to change the size of the array in one place - at the beginning change the size of the array in one place - at the beginning of the program. of the program.

The The square bracketssquare brackets in the array declaration are an in the array declaration are an operator in Java. They have a precedence relative to other operator in Java. They have a precedence relative to other operators i.e. the highest precedence.operators i.e. the highest precedence.

Both constants in the previous example were declared Both constants in the previous example were declared staticstatic because only copy of the size of the array is needed. because only copy of the size of the array is needed.

34

Bounds CheckingBounds Checking

If the array If the array codescodes can hold 100 values, it can only be indexed can hold 100 values, it can only be indexed using the numbers 0 to 99using the numbers 0 to 99

If If countcount has the value 100, then the following reference will has the value 100, then the following reference will cause an cause an ArrayOutOfBoundsExceptionArrayOutOfBoundsException::

System.out.println (codes[count]);System.out.println (codes[count]);

It’s common to introduce It’s common to introduce off-by-one errorsoff-by-one errors when using arrays when using arrays

for (int index=0; index <= 100; index++)codes[index] = index*50 + epsilon;

problem

35

Bounds CheckingBounds Checking

Once an array is created, it has a fixed size. An index used Once an array is created, it has a fixed size. An index used in an array reference must specify a valid element.in an array reference must specify a valid element.

That is, they must be in bounds (0 to N-1). That is, they must be in bounds (0 to N-1).

The Java interpreter will throw an exception if an array The Java interpreter will throw an exception if an array index is out of bounds. So that in our index is out of bounds. So that in our listlist array of 10 array of 10 elements, if you tried to access: elements, if you tried to access:

list[11]list[11]

an exception called an exception called ArrayIndexOutofBoundsException ArrayIndexOutofBoundsException would result.would result. The java index operator performs automatic The java index operator performs automatic bounds checking. bounds checking.

36

Bounds CheckingBounds Checking

Each array object has a public constant called Each array object has a public constant called lengthlength that that stores the size of the array. stores the size of the array.

It is referenced through the array name (just like any other It is referenced through the array name (just like any other object):object):

37

Length of an ArrayLength of an Array

scores.length;scores.length;

Length is a constant defined in the array class.Length is a constant defined in the array class.

scores. scores. lengthlength holds the number of elements allocated, holds the number of elements allocated, not the largest index. not the largest index.

That is, it holds the number of items you allocated for the That is, it holds the number of items you allocated for the array when you declared it..array when you declared it..

In the program Reverse_Numbers, an array is constructed to In the program Reverse_Numbers, an array is constructed to store numbers which are printed out in reverse.store numbers which are printed out in reverse.

38

ARRAYSARRAYS

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

Data structures like arrays are good when we know ahead Data structures like arrays are good when we know ahead of time how many elements are needed. of time how many elements are needed.

Other data structures like Other data structures like ArrayLists and linked listsArrayLists and linked lists can can be used when it is necessary to dynamically build a be used when it is necessary to dynamically build a structure to hold elements.structure to hold elements.

This is necessary when the number of elements is not This is necessary when the number of elements is not known ahead of time.known ahead of time.

39

Array Declarations RevisitedArray Declarations Revisited

The brackets of the array type can be associated with the The brackets of the array type can be associated with the element type or with the name of the array.Thereforeelement type or with the name of the array.Therefore

float[] prices;float[] prices;

andand

float prices[];float prices[];

are essentially equivalent. The first format is usually more are essentially equivalent. The first format is usually more readable as most variables are declared as: readable as most variables are declared as:

int sum, total, num // int sum, total, num // which is closer towhich is closer to int[] int[] sum, total, num // sum, total, num // versusversus int sum[], total, num // int sum[], total, num // which is confusingwhich is confusing

40

Initializer ListsInitializer Lists

An initializer list can be used to instantiate and initialize an An initializer list can be used to instantiate and initialize an array in one step.array in one step.

The values are delimited by braces and separated by The values are delimited by braces and separated by commas. Examples:commas. Examples:

int[] units = {147, 323, 89, 933, 540, int[] units = {147, 323, 89, 933, 540,

269, 97, 114, 298, 476};269, 97, 114, 298, 476};

char[] letter_grades = {'A', 'B', 'C',’D’};char[] letter_grades = {'A', 'B', 'C',’D’};

The array units is instantiated as an The array units is instantiated as an array of 10 ints, indexed from 0 to 9. array of 10 ints, indexed from 0 to 9.

The letter_grades array consists of an array of 4 The letter_grades array consists of an array of 4

characters.characters.

41

Initializer ListsInitializer Lists Note that when an initializer list is used:Note that when an initializer list is used:

the the newnew operator is not used operator is not used

no size value is specifiedno size value is specified

the type of each value in the list must be the same as the type of each value in the list must be the same as

the data type of the array.the data type of the array.

The size of the array is determined by the number The size of the array is determined by the number

of items in the initializer list. An initializer list can of items in the initializer list. An initializer list can

only be used in the declaration of an array.only be used in the declaration of an array.

The array size is set to the number of elements in The array size is set to the number of elements in

the initializer list.the initializer list.

42

When an array object is instantiated, the elements in the When an array object is instantiated, the elements in the array are initialized to the default value of the indicated data array are initialized to the default value of the indicated data type. type.

That is, it you declare an array of integers, each element is That is, it you declare an array of integers, each element is initialized to 0. initialized to 0.

However, it is always better to do your own initialization.However, it is always better to do your own initialization.

INITIALIZING ARRAYS

43

Array ExamplesArray Examples

int Numbers[] = new int[100] int Numbers[] = new int[100] Numbers[0] = 0; Numbers[0] = 0;

for(int i = 1; i < Numbers.length; i++) for(int i = 1; i < Numbers.length; i++) Numbers[i] = i + Numbers(i-1];Numbers[i] = i + Numbers(i-1];

We used the We used the lengthlength field, which is the field provided in the field, which is the field provided in the array class to contain the length of the array. This field is array class to contain the length of the array. This field is read-only.read-only.

Though arrays are objects and can access all the methods Though arrays are objects and can access all the methods that objects can, the syntax associated with them is that objects can, the syntax associated with them is somewhat different from that of other objects.somewhat different from that of other objects.

44

class Evens class Evens

{{ final int SIZE = 10; final int SIZE = 10;

public static void main(String[] args )public static void main(String[] args ) { { int [] intArray = new int [SIZE];int [] intArray = new int [SIZE];

for (j = 0; j < SIZE ; j++)for (j = 0; j < SIZE ; j++)

intArray[j] = 2 + 2 * j;intArray[j] = 2 + 2 * j;

System.out.println(“ System.out.println(“ Element Element Value Value “); “);

for (j = 0; j <= SIZE -1; j++) for (j = 0; j <= SIZE -1; j++) System.out.println(“ “ + j + “ “ intArray[j]);System.out.println(“ “ + j + “ “ intArray[j]);

} // method main } // method main

} class evens} class evens

45

class Sum {class Sum { public static void main(String[] args )public static void main(String[] args ) { { int [] intArray = { 1, 3, 5, 4, 7, 2, 16, 99, int [] intArray = { 1, 3, 5, 4, 7, 2, 16, 99, 45, 67 }; 45, 67 }; int total = 0; int total = 0;

// accumulate the total of the // accumulate the total of the

elements in the arrayelements in the array for (int j = 0; j < for (int j = 0; j < intArray.length; j++) intArray.length; j++) total = total + intArray[j]; total = total + intArray[j];

// // print resultsprint results System.out.println(“ Total array elements is “, System.out.println(“ Total array elements is “, total);total);

} // method main } // method main } // class Sum } // class Sum

output : Total of array elements is 287output : Total of array elements is 287

CLASS SUM

46

Command-Line ArgumentsCommand-Line Arguments

The The mainmain method has a parameter that it takes an array of method has a parameter that it takes an array of StringString objects objects as a parameter as a parameter

These values come from These values come from command-line argumentscommand-line arguments that are that are provided when the interpreter is invokedprovided when the interpreter is invoked

For example, the following invocation of the interpreter passes For example, the following invocation of the interpreter passes three three StringString objects into objects into mainmain::

> > java StateEval pennsylvania texas arizonajava StateEval pennsylvania texas arizona

These strings are stored at indexes 0-2 of the array parameter of These strings are stored at indexes 0-2 of the array parameter of the the mainmain method method

See See NameTag.javaNameTag.java (page 393) (page 393)

47

Examples of ArraysExamples of Arrays

class Echo {class Echo {

public static void main(String[] args )public static void main(String[] args ) { {

for (int j = 0; j < args.length; j++) for (int j = 0; j < args.length; j++)

System.out.print( arg[j] + “ “);System.out.print( arg[j] + “ “);

System.out.println (“ “);System.out.println (“ “);

} // method main} // method main

} // class Echo} // class Echo

output: prints out the contents of String[] args which is the values the output: prints out the contents of String[] args which is the values the user specified: user specified:

java Echo Mary Sam Bill printsjava Echo Mary Sam Bill prints

Mary Sam BillMary Sam Bill

48

ArrayCopyArrayCopy

It is possible to copy one array to another array with the It is possible to copy one array to another array with the arraycopy method: arraycopy method:

public static void arraycopy(Object sourceArray, int srcIndex, public static void arraycopy(Object sourceArray, int srcIndex, Object destination, int destIndex, int length).Object destination, int destIndex, int length).

The two objects are the The two objects are the sourcesource and and destination destination arrays, the arrays, the srcIndexsrcIndex and and destIndex destIndex are the starting points in the source are the starting points in the source and destination arrays, and and destination arrays, and length length is the number of elements is the number of elements to copy. E.g.:to copy. E.g.:

49

Copying ArraysCopying Arrays

public static void main(String args[]){public static void main(String args[]){ char[] copyFrom = { ‘d’,’e’,’c’,’a’, char[] copyFrom = { ‘d’,’e’,’c’,’a’, ‘f’, ‘f’,’e’,’i’ ‘n’};‘f’, ‘f’,’e’,’i’ ‘n’}; char[] copyTo = new char[] copyTo = new char[7];char[7]; System.arraycopy(copyFrom, 2, System.arraycopy(copyFrom, 2, copyTo, 0,7);copyTo, 0,7); } }

Arraycopy method begins the copy at element number 2 in Arraycopy method begins the copy at element number 2 in the source array (the source array (copyFromcopyFrom) which is element ‘c’. It ) which is element ‘c’. It copies it to the destination array (copies it to the destination array (copyTOcopyTO)) starting at index starting at index 0. It copies 7 elements, ‘c’ to ‘n’ into 0. It copies 7 elements, ‘c’ to ‘n’ into copyTOcopyTO. .

d e c a f f e i n

c a f f e i n

copyFrom

copyTO

0 1 2 3 4 5 6

2

50

Arrays of ObjectsArrays of Objects

Objects can have arrays as instance variables. Therefore, Objects can have arrays as instance variables. Therefore, fairly complex structures can be created simply with arrays fairly complex structures can be created simply with arrays and objects and objects

The software designer must carefully determine an The software designer must carefully determine an organization for each application.organization for each application.

51

The elements of an array can be object references. The The elements of an array can be object references. The declaration: declaration:

String[] words = new String[25];String[] words = new String[25];

reserves space to store 25 references to reserves space to store 25 references to StringString objects. objects.

It does NOT create the It does NOT create the StringString objects objects themselves: themselves:

ARRAYS

52

Arrays of ObjectsArrays of Objects

The The wordswords array when initially declared: array when initially declared:

words -

-

-

-

-

At this point, the following reference would throw a At this point, the following reference would throw a NullPointerExceptionNullPointerException::

System.out.println (words[0]);System.out.println (words[0]);

53

Arrays of ObjectsArrays of Objects

After some After some StringString objects are created and stored in the objects are created and stored in the array:array:

“friendship”

words

-

-

“loyalty”

“honor”

Address of string

54

Arrays of ObjectsArrays of Objects

Keep in mind that Keep in mind that StringString objects objects can be created using can be created using literalsliterals

The following declaration creates an array object called The following declaration creates an array object called verbsverbs and fills it with four and fills it with four StringString objects created using objects created using string literalsstring literals

String[] verbs = {"play", "work", "eat", "sleep"};

55

Initializing ArraysInitializing Arrays

// initializes the array// initializes the array

String[] name_list = {“Paul”, “Newman”, “Jessica”, “Ten”);String[] name_list = {“Paul”, “Newman”, “Jessica”, “Ten”);

Since a string literal instantiates a new string object, each string Since a string literal instantiates a new string object, each string literal in the initializer list creates an object for each element of literal in the initializer list creates an object for each element of the array. Hence: the array. Hence:

for(int name = 0; name < name_list.length; name++) for(int name = 0; name < name_list.length; name++) System.out.printl(name_list[name] + “ “);System.out.printl(name_list[name] + “ “);

OUTPUT = OUTPUT = Paul Newman Jessica TenPaul Newman Jessica Ten

56

Array of StringsArray of Strings Each object stored in an array can also be instantiated Each object stored in an array can also be instantiated

separately. e.g. separately. e.g. String[] phrase = new String[5];String[] phrase = new String[5];

phrase[0] = “Good Morning”;phrase[0] = “Good Morning”;

phrase[1] = “How are you”;phrase[1] = “How are you”;

phrase[2] = “Have a Good Day”;phrase[2] = “Have a Good Day”;

It is also possible to read in the elements of an array from It is also possible to read in the elements of an array from the user. In the the user. In the Presidents.javaPresidents.java program, the string program, the string elements in the array are instantiated by the elements in the array are instantiated by the readLinereadLine method. After reading the elements in, the names are method. After reading the elements in, the names are printed out in reverse order.printed out in reverse order.

57

Arrays of ObjectsArrays of Objects

The following example creates an array of The following example creates an array of GradeGrade objects, objects, each with a string representation and a numeric lower boundeach with a string representation and a numeric lower bound

See See GradeRange.javaGradeRange.java

See See Grade.javaGrade.java

Now let's look at an example that manages a collection of Now let's look at an example that manages a collection of CDCD objects objects

See See Tunes.javaTunes.java

See See CDCollection.javaCDCollection.java

See See CD.javaCD.java

58

Arrays of ObjectsArrays of Objects

A UML diagram for the A UML diagram for the TunesTunes program: program:

Tunes

+ main (args : String[]) : void

CDCollection

- collection : CD[]- count : int- totalCost : double

+ addCD (title : String, artist : String, cost : double, tracks : int) : void+ toString() : String- increaseSize() : voidCD

- title : String- artist : String- cost : double- tracks : int

+ toString() : String

*

1

59

OutlineOutline

Declaring and Using Arrays

Arrays of Objects

Two-Dimensional Arrays

Variable Length Parameter Lists

The ArrayList Class

Polygons and Polylines

Mouse Events and Key Events

60

Multidimensional ArraysMultidimensional Arrays

A A one-dimensional arrayone-dimensional array stores a simple list of values. stores a simple list of values.

A A two-dimensional arraytwo-dimensional array can be thought of as a table of can be thought of as a table of values, with rows and columns.values, with rows and columns.

A two-dimensional array element is referenced using two A two-dimensional array element is referenced using two index values. index values.

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

61

Two Dimensional ArraysTwo Dimensional Arrays

Actually Java does not support 2d arrays in the traditional Actually Java does not support 2d arrays in the traditional sense. What it does allow are one-dimensional arrays that sense. What it does allow are one-dimensional arrays that hold arrays as valueshold arrays as values..

In an initializer list, the first values represent the first In an initializer list, the first values represent the first element in the array.element in the array.

An initializer list can be used to create and set up a An initializer list can be used to create and set up a multidimensional array or values can be read into the array multidimensional array or values can be read into the array from a file or the keyboard.from a file or the keyboard.

62

Multi-dimensional Arrays.Multi-dimensional Arrays.

Each element in the list is itself an initializer list. It is Each element in the list is itself an initializer list. It is helpful to conceive of the 2D array as a table and a 3D array helpful to conceive of the 2D array as a table and a 3D array

as a cube. After that, it is not easy to conceive of anythingas a cube. After that, it is not easy to conceive of anything..

Note that each array dimension has its own Note that each array dimension has its own lengthlength

constantconstant..

For instance in the Multi_Arrays_Test program, the array is For instance in the Multi_Arrays_Test program, the array is initialized as:initialized as:

63

Two-Dimensional ArraysTwo-Dimensional Arrays

A A one-dimensional arrayone-dimensional array stores a list of elements stores a list of elements

A A two-dimensional arraytwo-dimensional array can be thought of as a table of can be thought of as a table of elements, with rows and columnselements, with rows and columns

onedimension

twodimensions

64

Two-Dimensional ArraysTwo-Dimensional Arrays

To be precise, in Java a two-dimensional array is an array To be precise, in Java a two-dimensional array is an array of arraysof arrays

A two-dimensional array is declared by specifying the size A two-dimensional array is declared by specifying the size of each dimension separately:of each dimension separately:

int[][] scores = new int[12][50];int[][] scores = new int[12][50];

A array element is referenced using two index values:A array element is referenced using two index values:

value = scores[3][6]value = scores[3][6]

The array stored in one row can be specified using one The array stored in one row can be specified using one indexindex

65

Two-Dimensional ArraysTwo-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[] array of integersarray of integers

table[5][12]table[5][12] intint integerinteger

See See TwoDArray.javaTwoDArray.java (page 399) (page 399)

See See SodaSurvey.javaSodaSurvey.java (page 400)(page 400)

66

Multidimensional ArraysMultidimensional Arrays

int[][] tableint[][] table = = { {28, 84, 47, 72}, {69, 26}, {91, 40, 28}, {42, { {28, 84, 47, 72}, {69, 26}, {91, 40, 28}, {42, 34, 37}, {13, 26, 57, 35} };34, 37}, {13, 26, 57, 35} };

The first values - 28, 84, 47 and 72 represent the first row The first values - 28, 84, 47 and 72 represent the first row of the array. The second set of values are the 2nd row:of the array. The second set of values are the 2nd row:

28 84 4728 84 47 72 72

69 2669 26

91 40 2891 40 28

42 34 3742 34 37

13 26 5713 26 57 35 35

67

import java.io.*;import java.io.*;

public class PassArrays{public class PassArrays{public static void main(String args[]){public static void main(String args[]){ int grades[][] = { { 100, 79, 83 }, { 44, 56, 67 }, { 95, 88, 99 } }; int grades[][] = { { 100, 79, 83 }, { 44, 56, 67 }, { 95, 88, 99 } }; printStudentScores( grades[1] ); printStudentScores( grades[1] ); printTestScores( grades, 1 ); printTestScores( grades, 1 ); } } public static void public static void printStudentScores( int[] row {printStudentScores( int[] row { System.out.print("Scores for student: "); System.out.print("Scores for student: ");

for (int i = 0; i < row.length; i++)for (int i = 0; i < row.length; i++) System.out.println(""); System.out.println(""); } } public static void printTestScores( int [][] gradebook, int testNo{ public static void printTestScores( int [][] gradebook, int testNo{ System.out.print("Scores for test " + testNo + " : "); System.out.print("Scores for test " + testNo + " : "); for (int row = 0; row < gradebook.length; row++ ) for (int row = 0; row < gradebook.length; row++ ) System.out.print(" " + gradebook[row][testNo]); System.out.print(" " + gradebook[row][testNo]);

System.out.println(""); System.out.println(""); } // method printTestScores } // method printTestScores } // class PassArrays } // class PassArrays

68

Variable Length Parameter ListsVariable Length Parameter Lists

Suppose we wanted to create a method that processed a Suppose we wanted to create a method that processed a different amount of data from one invocation to the nextdifferent amount of data from one invocation to the next

For example, let's define a method called For example, let's define a method called averageaverage that that returns the average of a set of integer parametersreturns the average of a set of integer parameters

// one call to average three valuesmean1 = average (42, 69, 37);

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

69

Variable Length Parameter ListsVariable Length Parameter Lists

We could define overloaded versions of the We could define overloaded versions of the averageaverage method method

• Downside: we'd need a separate version of the method Downside: we'd need a separate version of the method

for each parameter countfor each parameter count

We could define the method to accept an array of integersWe could define the method to accept an array of integers

• Downside: we'd have to create the array and store the Downside: we'd have to create the array and store the

integers prior to calling the method each timeintegers prior to calling the method each time

Instead, Java provides a convenient way to create Instead, Java provides a convenient way to create variable variable length parameter listslength parameter lists

70

Variable Length Parameter ListsVariable Length Parameter Lists

Using special syntax in the formal parameter list, we can Using special syntax in the formal parameter list, we can define a method to accept any number of parameters of the define a method to accept any number of parameters of the same typesame type

For each call, the parameters are automatically put into an For each call, the parameters are automatically put into an array for easy processing in the methodarray for easy processing in the method

public double average (int ... list){ // whatever} element

typearrayname

Indicates a variable length parameter list

71

Variable Length Parameter ListsVariable Length Parameter Lists

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

if (list.length != 0) { int sum = 0; for (int num : list) sum += num; result = (double)num / list.length; }

return result;}

72

Variable Length Parameter ListsVariable Length Parameter Lists

The type of the parameter can be any primitive or object The type of the parameter can be any primitive or object typetype

public void printGrades (Grade ... grades){ for (Grade letterGrade : grades) System.out.println (letterGrade);}

73

Variable Length Parameter ListsVariable Length Parameter Lists

A method that accepts a variable number of parameters can A method that accepts a variable number of parameters can also accept other parametersalso accept other parameters

The following method accepts an The following method accepts an intint, a , a StringString object, object, and a variable number of and a variable number of doubledouble values into an array values into an array called called numsnums

public void test (int count, String name, double ... nums){ // whatever}

74

Variable Length Parameter ListsVariable Length Parameter Lists

The varying number of parameters must come last in the The varying number of parameters must come last in the formal argumentsformal arguments

A single method cannot accept two sets of varying A single method cannot accept two sets of varying parametersparameters

Constructors can also be set up to accept a variable number Constructors can also be set up to accept a variable number of parametersof parameters

See See VariableParameters.javaVariableParameters.java (page 396) (page 396)

See See Family.javaFamily.java (page 397) (page 397)

75

SortingSorting

Sorting is the process of arranging a list of items into a well-Sorting is the process of arranging a list of items into a well-defined order.defined order.

If you want to alphabetize a list of name or put a list of If you want to alphabetize a list of name or put a list of survey results into descending numeric order, there are survey results into descending numeric order, there are several well-defined techniques to accomplish this task.several well-defined techniques to accomplish this task.

In fact, sorting is a classic area of Computer Science.In fact, sorting is a classic area of Computer Science.

We will examine two types of sorts: the Selections Sort and We will examine two types of sorts: the Selections Sort and Insertion Sort in a later lecture.Insertion Sort in a later lecture.

76

Arrays as ParametersArrays as Parameters

An entire array can be passed to a method as a parameter. An entire array can be passed to a method as a parameter. Like any other object, the reference to the array is passed, Like any other object, the reference to the array is passed, making the formal and actual parameters aliases of each making the formal and actual parameters aliases of each other.other.

Changing an array element in the method changes the Changing an array element in the method changes the original element. An array element can be passed to a original element. An array element can be passed to a method as well, and follow the parameter passing rules of method as well, and follow the parameter passing rules of that element's type.that element's type.

77

The The ArrayListArrayList Class Class

An object of class An object of class ArrayListArrayList is similar to an array in that is similar to an array in that it stores multiple valuesit stores multiple values

However, a However, a ArrayListArrayList

• only stores objects.only stores objects.

• can grow and shrink in sizecan grow and shrink in size

Service methods provided by the Service methods provided by the ArrayListArrayList t class are t class are used to interact with a used to interact with a ArrayListArrayList....

78

The The ArrayListArrayList Class Class

An important difference between an array and a An important difference between an array and a ArrayListArrayList is that a is that a ArrayListArrayList can be thought of as can be thought of as dynamic, that is, it is able to change its’ size as needed . dynamic, that is, it is able to change its’ size as needed .

A static structure like an array has a fixed size throughout A static structure like an array has a fixed size throughout its existence.its existence.

Each Each ArrayListArrayList initially has a certain amount of initially has a certain amount of memory space reserved for storing elements.memory space reserved for storing elements.

79

ArrayList ClassArrayList Class

If an element is added that doesn't fit in the existing If an element is added that doesn't fit in the existing space, more room is automatically acquired.space, more room is automatically acquired.

It accomplishes this by creating and destroying arrays. This It accomplishes this by creating and destroying arrays. This is not really efficient except for representing linear is not really efficient except for representing linear relationships.relationships.

80

The ArrayList ClassThe ArrayList Class

An An ArrayListArrayList is implemented using an array. is implemented using an array.

Whenever new space is required, a new, larger array is Whenever new space is required, a new, larger array is created, and the values are copied from the original to the created, and the values are copied from the original to the new array.new array.

To insert an element, existing elements are first copied, one To insert an element, existing elements are first copied, one by one, to another position in the array.by one, to another position in the array.

Therefore, the implementation of Therefore, the implementation of ArrayListArrayList in the API is in the API is not very efficientnot very efficient

81

The ArrayList ClassThe ArrayList Class

Elements can be inserted or removed with a single method Elements can be inserted or removed with a single method invocationinvocation

When an element is inserted, the other elements "move When an element is inserted, the other elements "move aside" to make roomaside" to make room

Likewise, when an element is removed, the list "collapses" Likewise, when an element is removed, the list "collapses" to close the gapto close the gap

The indexes of the elements adjust accordinglyThe indexes of the elements adjust accordingly

82

ArrayListsArrayLists

The major advantage of an The major advantage of an ArrayListArrayList that we can store that we can store different types of objects in it. different types of objects in it.

Since the methods are designed to accept references to any Since the methods are designed to accept references to any Object type, a reference to a string, an integer, a double Object type, a reference to a string, an integer, a double etc. can be passed. etc. can be passed.

NOTENOTE that if a primitive type is passed, it must be passed that if a primitive type is passed, it must be passed as an object using the Integer, or Double wrapper classes.as an object using the Integer, or Double wrapper classes.

83

ArrayList ClassArrayList Class

Thus to put an integer into an Thus to put an integer into an ArrayListArrayList you would have to first you would have to first create an integer object:create an integer object:

Integer num = new Integer(2); Integer num = new Integer(2); Double doublenum = new Double(2.98);Double doublenum = new Double(2.98);

The benefits of this are that different kinds of objects can be stored in The benefits of this are that different kinds of objects can be stored in the same data structure.the same data structure.

You must inport the java.util package to use an You must inport the java.util package to use an ArrayListArrayList

84

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

remove (Object element);remove (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 elementontains (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.

ensureCapacity()ensureCapacity() expands array by creating a new array. expands array by creating a new array.

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.

The ArrayList class Service methodsThe ArrayList class Service methods::

85

The ArrayList ClassThe ArrayList Class

An An ArrayListArrayList stores references to the stores references to the ObjectObject class, which class, which allows it to store any kind of objectallows it to store any kind of object

See See Beatles.javaBeatles.java (page 405) (page 405)

We can also define an We can also define an ArrayListArrayList object to accept a particular object to accept a particular type of objecttype of object

The following declaration creates an The following declaration creates an ArrayListArrayList object that object that only stores only stores FamilyFamily objects objects

ArrayListArrayList < <FamilyFamily> reunion = new > reunion = new ArrayListArrayList < <FamilyFamily>>

This is an example of This is an example of genericsgenerics, which are discussed further in , which are discussed further in Chapter 12Chapter 12