46
Think Java: How to Think Like a Computer Scientist 5.1.2 by Allen B. Downey Chapter 13: Arrays of Objects As in Chapter 11, we will be following a more standard approach than the one taken by Downey in this chapter. Instead, please refer to Chapter 5 Sections 5.1.4 and Chapter 7 of Eck, "Java Notes" , also linked from the class website.

Chapter 13: Arrays of Objects

  • Upload
    others

  • View
    4

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Chapter 13: Arrays of Objects

Think Java:

How to Think Like a Computer

Scientist

5.1.2

by Allen B. Downey

Chapter 13:

Arrays of Objects

As in Chapter 11, we will be following a more standard approach than the

one taken by Downey in this chapter. Instead, please refer to Chapter 5

Sections 5.1.4 and Chapter 7 of Eck, "Java Notes", also linked from the

class website.

Page 2: Chapter 13: Arrays of Objects

Review: Arrays

• An array is a set of values where each value is identified by an index.

int size = 6;

array elements

array index

1-2

Page 3: Chapter 13: Arrays of Objects

Access Array Elements using the [ ] operator

Note: as with String, elements go from 0 to 3 count[4] = 2; ArrayOutOfBounds Execption

1-3

Page 4: Chapter 13: Arrays of Objects

8-4

Arrays of Primitives (char, int, double, boolean)

• When we create an array of primitive data, the data is stored in each element of the array:

char[] grades = {'A','B','D','F','B'};

boolean[] pass = new boolean[grades.length];

'A' 'B' 'D' 'F' 'B'

0 1 2 3 4 grades

false false false false false

0 1 2 3 4 pass

Page 5: Chapter 13: Arrays of Objects

8-5

Arrays of Primitives We usually process arrays using for loops

for (int k = 0; k < grades.length; k++)

if (grades[k] >= 'A' && grades[k] <= 'C')

pass[k] == true;

'A' 'B' 'D' 'F' 'B'

0 1 2 3 4 grades

false false false false false

0 1 2 3 4 pass

k

Page 6: Chapter 13: Arrays of Objects

We can also create our own Objects

• Remember, object variables store a reference to where the object is stored

Time t = new Time(11,30,40);

1-6

t hour 11

minute 30

second 40

Page 7: Chapter 13: Arrays of Objects

Arrays of Objects: Each element is a reference to an object

Time [] appts = new Time[5];

appts[0] = new Time(9,20,0);

appts[1] = new Time(11,15,0);

1-7

null null null null null

0 1 2 3 4 appts

hour 9

minute 20

second 0

hour 11

minute 15

second 0

Page 8: Chapter 13: Arrays of Objects

To modify an object in an array, specify array[index] first

appts[0].hour = 12;

appts[1].minute = 30;

appts[2].second = 15;

1-8

null null null null null

0 1 2 3 4 appts

hour 9

minute 20

second 0

hour 11

minute 15

second 0

// Null Pointer Exception!

Page 9: Chapter 13: Arrays of Objects

If we make the instance variables private, we have to use the set methods

appts[0].setHour(12);

appts[1].setMinute(30);

appts[2].setSecond(15);

1-9

null null null null null

0 1 2 3 4 appts

hour 9

minute 20

second 0

hour 11

minute 15

second 0

// Null Pointer Exception!

Page 10: Chapter 13: Arrays of Objects

You can use a for loop to create all the objects

for (int k = 0; k < appts.length; k++)

appts[k] = new Time();

1-10

0 1 2 3 4 appts

Page 11: Chapter 13: Arrays of Objects

And another for loop to print them all out

for (int k = 0; k < appts.length; k++)

appts[k].print();

1-11

0 1 2 3 4 appts

Console 12:00:00 12:00:00 12:00:00 12:00:00 12:00:00

Page 12: Chapter 13: Arrays of Objects

For Lab 13 we will practice creating arrays of different objects

1-12

Page 13: Chapter 13: Arrays of Objects

• This method would be defined in the ArrayOfObjects class

• Calling the method from main:

Writing Methods that Process Arrays

1-13

public static void printAllTimes(Time [] times)

{

for (int k = 0; k < times.length; k++)

times[k].print();

System.out.println(""); // go to new line

}

printAllTimes(appts);

s

Page 14: Chapter 13: Arrays of Objects

Other Classes we will work with in Lab13

• String:

String name = "Jasper";

• Employee:

Employee cpa = new Employee("Bill",1111,37000);

1-14

Page 15: Chapter 13: Arrays of Objects

Arrays of Objects you can create

• Array of String:

String [] dictionary = new String[100000];

String [] names = {"Joe","Allie","Sam","Fay"};

• Array of Scrabble Tile objects:

Tile [] letterBag = new Tile[99];

Tile [] player1rack = new Tile[7];

• Array of Employee:

Employee [] marketingTeam = new Employee[15];

• Array of Card:

Card [] pokerHand = new Card[4];

1-15

Page 16: Chapter 13: Arrays of Objects

Do Lab 13 Problems 0 through 3

• First define the Employee class (review)

1-16

Page 17: Chapter 13: Arrays of Objects

Part B Lecture

• Additional OOP (object) methods

– toString

– equals

– compareTo

• A Card class

• Reading data from a file into an array

• Working with partially filled arrays

1-17

Page 18: Chapter 13: Arrays of Objects

Our OOP Model for objects

• Each class that can make objects has

– private instance variables

– accessor methods (get)

– modifier methods (set)

– print method

1-18

Page 19: Chapter 13: Arrays of Objects

Example: Time class

• instance variables:

– int hour, minute; double second;

• accessor methods

– getHour, getMinute, getSecond

• modifier methods

– setHour, setMinute, setSecond

• print method

– print

• We are going to add 3 more items to this list

1-19

Page 20: Chapter 13: Arrays of Objects

Additional methods for OOP

• The following slides illustrate three other very useful methods you will want to incorporate into your own defined classes to make it easy to work with their objects (instances) – toString

– equals

– compareTo

• We will demonstrate implementing these for the Time and Employ class in lab13

1-20

Page 21: Chapter 13: Arrays of Objects

The toString method

• Every object type has a method toString

– returns a string representation of the object

• When you System.out.print an object

– Java calls the object’s toString method automatically

– Default version just returns the object's Hex address

– System.out.print("The time is " + now);

– prints:

The time is Time@80cc7c0 1-21

Page 22: Chapter 13: Arrays of Objects

Define a toString method for Time

• Can override the default behavior with own def: public String toString() {

return hour + ":" +

minute + ":" +

second;

}

• Allows for better output: – System.out.print("The time is " + now);

– prints: The time is 11:35:40

1-22

Page 23: Chapter 13: Arrays of Objects

You could also invoke toString explicitly

• Just like any other object method

Time now = new Time(12,23,47);

String s = now.toString();

1-23

Page 24: Chapter 13: Arrays of Objects

Try this out now in your lab13 project

– write the toString method

• for Time and Employee class

– demo by changing the print statements in ArraysOfObjects

1-24

Page 25: Chapter 13: Arrays of Objects

Notions of same-ness with objects

• What is the meaning of "same"?

– "Chris and I have the same car"

•Same make and model

•But…two different cars

– "Chris and I have the same mother"

•his mother and mine are one person

1-25

Page 26: Chapter 13: Arrays of Objects

Card Class

• This was part of assignment 11

• Cards are represented by char for suit:

– 'C' = Clubs, 'D' = Diamonds, 'H' = Hearts, 'S' = Spades

• And an integer for rank:

– 1 = Ace, 2-10, 11=Jack, 12=Queen, 13=King

• Card mystery = new Card('H',13);

1-26

class Card{

private char suit;

private int rank;

Page 27: Chapter 13: Arrays of Objects

Both possibilities of "sameness" with objects in Java

• Card1 and Card2 contain the same data

• Card1 and Card2 refer to the same object

1-27

Page 28: Chapter 13: Arrays of Objects

Two references to the same object

• To see if two references refer to the same object, we use the == operator

• References to the same object are identical 1-28

Page 29: Chapter 13: Arrays of Objects

Two Objects with the Same Data

• To see if two object contain the same data,

write a method, equals, in the Card class

• References to objects with same data are equivalent. 1-29

Page 30: Chapter 13: Arrays of Objects

The equals Method

• To check equivalence, it is standard practice to write a method with the name equals.

1-30

public boolean equals(Card that) {

return (this.suit == that.suit &&

this.rank == that.rank;) }

Page 31: Chapter 13: Arrays of Objects

Application to String Objects

• Using == to check for String equivalence is an error:

String s1 = "hello";

String s2 = "hello";

if (s1 == s2)

System.out.println("same");

else

System.out.println("Not the same");

1-31

Two different objects, with same data

false, not identical

___________

Page 32: Chapter 13: Arrays of Objects

Correct way to check for String Equivalence

• The .equals method for String objects

String s1 = "hello";

String s2 = "hello";

if (s1.equals(s2))

System.out.println("same");

else

System.out.println("Not the same");

1-32

Two different objects, with same data

true, equivalent objects

_____

Page 33: Chapter 13: Arrays of Objects

Try this out now in your lab13 project

– write an equals method

• for Time and Employee class

– demo by comparing Time and Employee objects in ArraysOfObjects

1-33

Page 34: Chapter 13: Arrays of Objects

Comparing Primitives and Objects

• Comparing primitives: use <,>,==,<=,>=,!=

int x = 4, y = 6;

if (x < y) System.out.println("x < y");

• Comparing String objects:

String s1 = "apple", s2 = "apply";

if (s1.compareTo(s2) < 0)

System.out.println("s1 before s2");

1-34

Page 35: Chapter 13: Arrays of Objects

The compareTo Method

• How to order cards?

– By suit, then by rank? or, by rank, then by suit?

– Cards come ordered by suit, then rank

• First compare suit:

• Then compare rank:

• If neither of the above is true, must be same

– just return 0

1-35

if (this.suit > that.suit) return 1;

if (this.suit < that.suit) return -1;

if (this.rank > that.rank) return 1;

if (this.rank < that.rank) return -1;

Page 36: Chapter 13: Arrays of Objects

The compareTo method for Card class

class Card{

private char suit;

private int rank;

...

public int compareTo(Card that) {

if (this.suit > that.suit) return 1;

if (this.suit < that.suit) return -1;

if (this.rank > that.rank) return 1;

if (this.rank < that.rank) return -1;

return 0;

}

}

1-36

Page 37: Chapter 13: Arrays of Objects

Try this out now in your lab13 project

– write the compareTo method

• for Time class – compare hour, then min, then sec

• for Employee class – compare name, then if they are the same, by id

– demo by comparing Time and Employee objects in ArraysOfObjects

1-37

Page 38: Chapter 13: Arrays of Objects

Arrays of Cards

• Create an array to hold 52 cards

• The array contains references to objects

– does not hold objects themselves

– cards[0].print();

1-38

// Null Pointer Exception!

Page 39: Chapter 13: Arrays of Objects

Creating a Deck of Cards

• 1 way is to have the user enter all the values for a deck of Cards

– not practical

• Another way is to read a list of Card

values from a file, say cards.txt

1-39

Page 40: Chapter 13: Arrays of Objects

Read a Deck of Cards from a file

• Declare a file Scanner:

• Read file data into temp local variables

• Create a new Card object based on values read

• Store tempCard in array

• Put in a loop that repeats 52 times

1-40

Scanner inputFile = new Scanner(new File("cards.txt"));

char tempSuit = inputFile.next().charAt(0);

int tempRank = inputFile.nextInt();

Card tempCard = new Card(tempSuit, tempRank);

deck[index] = tempCard;

Page 41: Chapter 13: Arrays of Objects

Read a Deck of Cards from a file

• You will also need to import:

import java.util.Scanner;

import java.io.File;

import java.io.FileNotFoundException;

• And tell Java your main method (potentially)

throws FileNotFoundException

1-41

Page 42: Chapter 13: Arrays of Objects

The resulting array of cards after loop

1-42

Page 43: Chapter 13: Arrays of Objects

The printDeck method

• Encode a traversal of cards array into a method public static void printDeck(Card [] cards)

{

for (int k = 0; k < cards.length; k++)

cards[k].print();

System.out.println(""); // go to newline

}

1-43

Page 44: Chapter 13: Arrays of Objects

8-44

Partially Filled Arrays • Typically, if the amount of data that an array must hold is unknown:

– size the array to the largest expected number of elements. – use a counting variable to keep track of how much valid data is in the

array. …

int[] array = new int[100];

int count = 0;

System.out.print("Enter a number or -1 to quit: ");

number = keyboard.nextInt();

while (number != -1 && count <= 99)

{

array[count] = number;

count++;

System.out.print("Enter a number or -1 to quit: ");

number = keyboard.nextInt();

}

input, number and keyboard were

previously declared and keyboard

references a Scanner object

Page 45: Chapter 13: Arrays of Objects

8-45

Processing a Partially Filled Array • After the code in the previous slide, we can process the

array with a loop that goes up to count:

for ( int k = 0; k < count; k++) System.out.println( array[k] );

• Only processes the cells that have been filled with data

• the ArrayList class (next Lecture) shows a better way to handle arrays with fluctuating size

Page 46: Chapter 13: Arrays of Objects

Start Assignment 13

1-46