84
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 additional techniques for managing strings 1

O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

Embed Size (px)

DESCRIPTION

T HE STATIC M ODIFIER Unless otherwise specified, a member declared within a class is an instance variable. In the following Numbers class, there are Two instance variables, an integer - num1 an integer - count plus one accessor method - ReturnNum(). 3

Citation preview

Page 1: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

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 additional techniques for managing strings

1

Page 2: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

STATIC VARIABLES - DETAILS

Normally, each object has its own data space.

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

private static int count;

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

Static variables are sometimes called class variables.

Chap6

2

Page 3: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

THE STATIC MODIFIER Unless otherwise specified, a member

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

Two instance variables, an integer - num1 an integer - count plus one accessor method - ReturnNum().

3

Page 4: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

In this version , there are two instance variables.class Number {

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

num1 = value;

count ++; }

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

Page 5: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

STATIC VARIABLES Each object that it is created in the

Numbers class contains a:

copy of the num1 and count variables and has access to the ReturnNum method.

Each object has unique values for the num1 instance variable and count.

5

Page 6: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

In the main method of the Driver class, class Testclass Test{ public static void main(String args[]) { Number num1 = new Number(17); Number num2 = new Number(12);

}

In memory, number hasa copy of num1 and count

6

Number 58

Number 2 60

58 num1 17

count 1

60 num2 12 count 1

Page 7: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

copy of the variable or method is created. class Number {

static int count = 0; // one copy for all instances

private int num1; public Number(int value) {

count++; num1 = value ;

} public int returnNum() {

return num1; }

}7

Static Variables

Page 8: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

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 for the classbut there is one copy of count for the class

num1 57

num2 60

57 num1 17

60 num1 20

62 count 2

Page 9: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

STATIC VARIABLES

Memory space for a static variable is created when the class is first starts to execute

All objects instantiated from the class share its static variables – only copy exists for all objects

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

9

Page 10: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

STATIC VARIABLES

When used properly, static variables are very effective.

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

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

They just have access to their value – they share them.

10

Page 11: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

CLASS STUDENT

class Student { private static int count = 0; // a static

variable

private int SocSecNum; private String name; public Student () { //CONSTRUCTOR count = count + 1; } // constructor Student public int ReturnCount() {

return count;} // method ReturnCount

11

Page 12: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

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

E.g. with every new Student object, you get a new name variable associated with the new Student object but it shares the static variable count

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

12

Instance Variable and Methods

Page 13: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

THE STATIC MODIFIER The static modifier can be applied to

variables or methods.

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

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

Chap6

13

Page 14: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

STATIC METHODS Static methods are invoked using the

class name and are sometimes called class methods.

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

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

14

Page 15: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

THE STATIC MODIFIER So, you create static methods. To invoke these

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

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

Math.abs (num) // absolute value Character.toUppercase (c) // uppercases a char

y = Math.sqrt.(x)

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

15

Page 16: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

STATIC METHODS

Normally, we invoke a method through an instance (an object) of a class. We create an object and then call the methods in the class

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

Chap6

16

Page 17: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

STATIC METHODS

17

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

Page 18: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

STATIC CLASS MEMBERS Static methods and static variables often

work together The following example keeps track of how

many Slogan objects have been created using a static variable, and makes that information available using a static method

See SloganCounter.java (page 294) See Slogan.java (page 295)

18

Page 19: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

19

public class Slogan{ private String phrase; private static int count = 0;

//----------------------------------------------------------------- // Constructor: Sets up the slogan and counts the number of // instances created. //----------------------------------------------------------------- public Slogan (String str) { phrase = str; count++; }

Page 20: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

20

//----------------------------------------------------------------- // Returns this slogan as a string. //----------------------------------------------------------------- public String toString() { return phrase; }

//----------------------------------------------------------------- // Returns the number of instances of this class that have //been created. //----------------------------------------------------------------- public static int getCount () { return count; }}

Page 21: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

21

// Demonstrates the use of the static modifier.public class SloganCounter{ public static void main (String[] args) { Slogan obj; obj = new Slogan ("Remember the Alamo."); System.out.println (obj);

obj = new Slogan ("Don't Worry. Be Happy."); System.out.println (obj);

obj = new Slogan ("Live Free or Die."); System.out.println (obj);

obj = new Slogan ("Talk is Cheap."); System.out.println (obj);

System.out.println ("Slogans created: " + Slogan.getCount()); } }// Output: prints out all the slogans and the count which is 4

Page 22: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

ARRAYS

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

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

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

22

0 1 2 3 4 5 6 7 8 9

scores 79 87 94 82 67 98 87 81 74 91

Page 23: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

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

23

Page 24: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

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

24

0 1 2 3 4 5 6 7 8 9

scores 79 87 94 82 67 98 87 81 74 91

Page 25: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

ARRAYS

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

scores[4]; refers to the value 67 (which is the 5th value

in the array). Scores[0] is first element in the array - all

indexes start at 0. The value stored in the 3rd index is the 4th element.

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

Page 26: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

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) called intArray would be located in memory like this:

26

1 Location 23 90

40 60 70 75 8090

scores

01 2 3 4 5 6 78

View of Memory

Page 27: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

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.

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.

27

Page 28: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

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.

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

28

Page 29: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

ARRAYS

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

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

29

Page 30: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

DECLARING ARRAYS

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

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.

30

Page 31: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

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.

31

Page 32: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

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

32

Page 33: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

ARRAYSYou 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

33

Page 34: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

class Basic_Array { final static int LIMIT = 10; // value will not change as

final static int INCREMENT = 10; // only one copy needed

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

for (int value : list) // forEach value in list System.out.print (value + " ");

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

34

Creates an array with 10 elements

Page 35: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

LIST

35

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 36: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

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.

36

Page 37: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

37

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

Page 38: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

BOUNDS CHECKING

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

That is, they must be in bounds (0 to N-1). The Java interpreter will throw an exception if an

array index is out of bounds. So that in our list array of 10 elements, if you tried to access: list[11] an exception called ArrayIndexOutofBoundsException would result. The java index operator performs automatic bounds checking.

38

Page 39: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

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):

39

Page 40: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

LENGTH OF AN ARRAYscores.length;

Length is a constant defined in the array class.

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

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

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

Page 41: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

ARRAYS Arrays are considered to be a static structure

because they have a fixed size. They cannot shrink or grow in size.

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

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

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

Page 42: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

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 array units is instantiated as an array of 10 ints, indexed from 0 to 9.

The letter_grades array consists of an array

of 4 characters.42

Page 43: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

INITIALIZER LISTS Note that when an initializer list is used:

the new operator is not used no size value is specified

the type of each value in the list must be the same as the data type of the array.

The size of the array is determined by the number of items in the initializer list. An initializer list can only be used in the declaration of an array.

The array size is set to the number of elements in the initializer list.

43

Page 44: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

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

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

However, it is always better to do your own

initialization.

44

INITIALIZING ARRAYS

Page 45: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

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

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

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

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

45

Page 46: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

class Evens {

final int SIZE = 10; public static void main(String[] args ) {

int [] intArray = new int [SIZE];

for (j = 0; j < SIZE ; j++) intArray[j] = 2 + 2 * j;

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

} // method main } class evens

46

Page 47: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

class Sum { public static void main(String[] args ) { // initialize the array with ints int [] intArray = { 1, 3, 5, 4, 7, 2, 16, 99, 45,

67 }; int total = 0; //

accumulate the total of the elements in the array

for (int j = 0; j < intArray.length; j++) total = total + intArray[j]; // print results System.out.println(“ Total array elements is “, total);

} // method main } // class Sum output : Total of array elements is 287 47

Page 48: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

ARRAYCOPY It is possible to copy one array to another

array with the arraycopy method: public static void arraycopy(Object

sourceArray, int srcIndex, Object destination, int destIndex, int length).

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

48

Page 49: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

COPYING ARRAYS

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

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

49

d e c a f f e i n

c a f f e i n

copyFrom

copyTO0 1 2 3 4 5 6

2

Page 50: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

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

String[] words = new String[25];

reserves space to store 25 references to String objects.

It does NOT create the String objects themselves: 50

ARRAYS

Page 51: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

ARRAYS OF OBJECTS The words array when initially declared:

51

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

address

Page 52: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

ARRAYS OF OBJECTS After some String objects are created and

stored in the array:

52

“friendship”

words

--

“loyalty”“honor”

Address of string

Page 53: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

ARRAYS OF OBJECTS Keep in mind that String objects can be created

using literals

The following declaration creates an array object called verbs and fills it with four String objects created using string literals

53

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

Page 54: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

INITIALIZING ARRAYS// initializes the arrayString[] name_list = {“Paul”, “Newman”,

“Jessica”, “Ten”); Since a string literal instantiates a new string

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

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

OUTPUT = Paul Newman Jessica Ten

54

Page 55: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

ARRAY OF STRINGS Each object stored in an array can also be

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

phrase[0] = “Good Morning”;

phrase[1] = “How are you”; phrase[2] = “Have a Good Day”;

It is also possible to read in the elements of an array from the user.

55

Page 56: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

ARRAYS OF OBJECTS The following example creates an array of Grade objects, each with a string representation and a numeric lower bound

See GradeRange.java See Grade.java

56

Page 57: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

57

// Represents a school grade.//**************************************************public class Grade{ private String name; private int lowerBound;

//----------------------------------------------------------------- // Constructor: Sets up this Grade object with the specified // grade name and numeric lower bound. //----------------------------------------------------------------- public Grade (String grade, int cutoff) { name = grade; lowerBound = cutoff; }

Page 58: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

58

//----------------------------------------------------------------- // Returns a string representation of this grade. //----------------------------------------------------------------- public String toString() { return name + "\t" + lowerBound; }

//----------------------------------------------------------------- // Name mutator. //----------------------------------------------------------------- public void setName (String grade) { name = grade; }

Page 59: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

59

//----------------------------------------------------------------- // Lower bound mutator. //----------------------------------------------------------------- public void setLowerBound (int cutoff) { lowerBound = cutoff; }

//----------------------------------------------------------------- // Lower bound accessor. //----------------------------------------------------------------- public int getLowerBound() { return lowerBound; }}

Page 60: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

60

public class GradeRange{ //----------------------------------------------------------------- // Creates an array of Grade objects and prints them. //----------------------------------------------------------------- public static void main (String[] args) { Grade[] grades = { new Grade("A", 95), new Grade("A-", 90), new Grade("B+", 87), new Grade("B", 85), new Grade("B-", 80), new Grade("C+", 77), new Grade("C", 75), new Grade("C-", 70), new Grade("D+", 67), new Grade("D", 65), new Grade("D-", 60), new Grade("F", 0) };

for (Grade letterGrade : grades) System.out.println (letterGrade); / / which is the same as: for ( int index = 0; index < 5; index ++ System.out.println(grades[index]; }}

Page 61: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

61

// shortcut instantiations of array Grade[] grades = { new Grade("A", 95), new Grade("A-", 90), new Grade("B+", 87), new Grade("B", 85), new Grade("B-", 80), new Grade("C+", 77), new Grade("C", 75), new Grade("C-", 70), new Grade("D+", 67), new Grade("D", 65), new Grade("D-", 60), new Grade("F", 0) };

If we did not do the above shortcut instantiations, we would have to fill the array as below:

grades[0] = new Grade(“A”, 95);grades[1] = new Grade(“A-”, 90);grades[2] = new Grade(“B+”, 87);grades[3] = new Grade(“B”, 85);grades[4] = new Grade(“B-”, 80);….. And so on

Page 62: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

OUTLINE

62

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

Page 63: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

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.

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

63

Page 64: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

TWO DIMENSIONAL ARRAYS Actually Java does not support 2d arrays in

the traditional sense. What it does allow are one-dimensional arrays that hold arrays as values.

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

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

Page 65: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

MULTI-DIMENSIONAL ARRAYS.

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 as a cube. After that, it is not easy to conceive of anything.

Note that each array dimension has its own length constant.

65

Page 66: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

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

66

onedimension

twodimensions

Page 67: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

TWO-DIMENSIONAL ARRAYS To be precise, in Java a two-dimensional array is

an array of 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 67

Page 68: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

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[] array of integers - array of integers - A ROW A ROW IN THE TABLEIN THE TABLE

table[5][12]table[5][12] intint Integer – Integer – an int value in a an int value in a cell of the tablecell of the table

68

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

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

Page 69: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

69

// Class Soda_Scores stores the results of the survey in a 2D// array of integers representing individual respondents ratings of 4 sodas and contains the methods to perform some basic analysis.//-------------------------------------------------------------------class Soda_Scores {

private final int RESPONDENTS = 10; private final int SODAS = 4;

// each row represents one of the sodas, each column represents one of the //respondents private int[][] results = { {3, 4, 5, 2, 1, 4, 3, 2, 4, 4}, // soda 1 {2, 4, 3, 4, 3, 3, 2, 1, 2, 2}, // soda 2 {3, 5, 4, 5, 5, 3, 2, 5, 5, 5}, // soda 3 {1, 1, 1, 3, 1, 2, 1, 3, 2, 4} }; // soda 4

//============================================= // Returns the number of sodas used in the survey. /=============================================== public int num_sodas() { return SODAS; } // method num_sodas

Page 70: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

70

//============================================== // Determines if the specified soda is worthy of future // development by seeing if at least half of the survey // respondents scored the soda at or above a particular // level. Goes through the columns and checks values// variable soda represents a row /============================================== public boolean worthy (int soda, int level) {

int count = 0;

for (int person=0; person < results[soda].length; person++) if (results[soda][person] >= level) // scored above level count++;

return (count > RESPONDENTS/2);

} // method worthy

} // class Soda_Scores

Page 71: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

71

// Class Soda_Survey contains the driver of a program that produces the results of a soda taste test.//-------------------------------------------------------------------class Soda_Survey { // Creates a Soda_Scores object, then determines and prints if each tested soda is worthy of future development. //============================================ public static void main (String[] args) {

Soda_Scores test = new Soda_Scores();

// goes through the four rows and calls the method worthy() in //Soda_Scores which goes through the columns and checks for levels //greater than 3 for (int soda=0; soda < test.num_sodas(); soda++) System.out.println ("Soda " + (soda+1) + " is " + (test.worthy(soda, 3) ? "worthy." : "not worthy."));

} // method main

} // class Soda_Survey

Page 72: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

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 47 7269 2691 40 2842 34 3713 26 57 35 72

Page 73: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

import java.io.*;

public class PassArrays{public static void main(String args[]){ // initialize the array int grades[][] = { { 100, 79, 83 }, { 44, 56, 67 }, { 95, 88,

99 } }; // call methods to print a row printStudentScores( grades[1] );} // represents a row in the array

public static void printStudentScores( int[] row)

{ System.out.print("Scores for student: ");

for (int i = 0; i < row.length; i++) System.out.println(""); }

73

Page 74: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

ARRAYS AS PARAMETERS

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

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

74

Page 75: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

75

public class PassArrays{public static void main(String args[]){ // initialize the array int grades[][] = { { 100, 79, 83 }, { 44, 56, 67 }, { 95, 88, 99 } }; // call methods to print row 1 – grades[1] printStudentScores( grades[1] );} // represents a row in the array, this changes all the

values in that row

public static void printStudentScores( int[] row) { System.out.print("Scores for student: ");

for (int i = 0; i < row.length; i++) row[i] = 40; }

Result: All values in row 1 (grades[1] have been changed to 40

Page 76: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

THE ARRAYLIST CLASS An object of class ArrayList is similar to an

array in that it stores multiple values

However, a ArrayListonly stores objects.can grow and shrink in size

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

76

Page 77: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

THE ARRAYLIST CLASS An important difference between an array and

a ArrayList is that a ArrayList can be thought of as 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.

77

Page 78: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

ARRAYLIST CLASS If an element is added that doesn't fit

in the existing space, more room is automatically acquired.

It accomplishes this by creating and destroying arrays. This is not really efficient.

However it is necessary if want the flexibility to enlarge arrays.

78

Page 79: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

THE ARRAYLIST CLASS

An ArrayList is implemented using an array.

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

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

79

Page 80: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

THE ARRAYLIST CLASS Elements can be inserted or removed with a

single method invocation When an element is inserted, the other

elements "move up or down " to make room

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

The indexes of the elements adjust accordingly

80

Page 81: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

ARRAYLISTS

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

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

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

81

Page 82: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

ARRAYLIST CLASS Previoiusly, to put an integer into an ArrayList you

would have to first create an integer object:

ArrayList list = new ArrayList();Integer num = new Integer(10);

list.add(num); But now Java will automatically change an int to an

object for you so that you can code: list.add(10); // java changes 10 to an Integer

object

You must inport the java.util package to use an ArrayList 82

Page 83: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

83

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

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

lastIndexOf(Object elementlastIndexOf(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::

Page 84: O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array

THE ARRAYLIST CLASS An ArrayList stores references to the Object

class, which allows it to store any kind of object

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

The following declaration creates an ArrayList object that only stores Family objectsArrayList <Family> reunion = new ArrayList <Family>

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