Chapter 4 Grouping Objects. Flexible Sized Collections When writing a program, we often need to be...

26
Chapter 4 Chapter 4 Grouping Objects Grouping Objects

Transcript of Chapter 4 Grouping Objects. Flexible Sized Collections When writing a program, we often need to be...

Page 1: Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.

Chapter 4Chapter 4

Grouping ObjectsGrouping Objects

Page 2: Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.

Flexible Sized CollectionsFlexible Sized Collections

When writing a program, we often need When writing a program, we often need to be able to group objects into to be able to group objects into collectionscollections

It is typical that the number of items to be It is typical that the number of items to be stored will vary over timestored will vary over time

We could create a class with a lot of fixed We could create a class with a lot of fixed fields, but in general this will not workfields, but in general this will not work

Page 3: Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.

Personal Notebook Personal Notebook ExampleExample

We will model a personal notebookWe will model a personal notebook Allow notes to be storedAllow notes to be stored No limit to the number of notes storedNo limit to the number of notes stored Show individual notesShow individual notes Tells how many notes are storedTells how many notes are stored

Page 4: Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.

Library ClassesLibrary Classes

One feature of OO languages, is the One feature of OO languages, is the accompanying accompanying class librariesclass libraries

Library typically contain hundreds or Library typically contain hundreds or thousands of different classesthousands of different classes

Java calls these libraries Java calls these libraries packagespackages We use library classes exactly the same We use library classes exactly the same

way we would our own classesway we would our own classes Instances are constructed using new, and the Instances are constructed using new, and the

classes have fields, constructors and methodsclasses have fields, constructors and methods

Page 5: Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.

Actual CodeActual Code

Let’s look at the Notebook class code.Let’s look at the Notebook class code. Notebook ProjectNotebook Project The very first line shows how we access the The very first line shows how we access the

package, using an package, using an import statementimport statement import java.util.ArrayList;import java.util.ArrayList;

Import statements must always be placed Import statements must always be placed before class definitions in a file.before class definitions in a file.

Once a class name has been imported, we Once a class name has been imported, we can use that class as if it were our own.can use that class as if it were our own.

Page 6: Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.

Object Structures with Object Structures with CollectionsCollections

There are at least three important featuresThere are at least three important features It is able to increase its internal capacity as It is able to increase its internal capacity as

required: as more items are added, it simply required: as more items are added, it simply makes enough room for them.makes enough room for them.

It keeps its own private count of how many It keeps its own private count of how many items it is currently storing. Its size method items it is currently storing. Its size method returns the number of objects currently storedreturns the number of objects currently stored

It maintains the order of items you insert into it. It maintains the order of items you insert into it. You can later retrieve them in the same order.You can later retrieve them in the same order.

Page 7: Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.

Numbering within Numbering within CollectionsCollections

It is necessary to use values starting at It is necessary to use values starting at zero.zero.

Items are stored in the ArrayList starting a Items are stored in the ArrayList starting a number position zeronumber position zero

The position is known as the The position is known as the indexindex First is given index 0, the next is index 1, First is given index 0, the next is index 1,

…… It is a common mistake to try to access a It is a common mistake to try to access a

collection outside the valid indices.collection outside the valid indices.

Page 8: Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.

Removing ElementsRemoving Elements

When a user wants to remove an note, we can When a user wants to remove an note, we can invoke the remove method of the notebook invoke the remove method of the notebook objectobject

One complication of the removal process is One complication of the removal process is that it can change the index values at which that it can change the index values at which notes are storednotes are stored

If a note with a low index value is removed, If a note with a low index value is removed, then the collection moves all notes forward to then the collection moves all notes forward to fill the hole.fill the hole.

Furthermore, it is possible to insert into other Furthermore, it is possible to insert into other than at the end.than at the end.

Page 9: Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.

Processing a whole Processing a whole collectioncollection

It would be useful to list all the notes in It would be useful to list all the notes in the notebook it find where all of them arethe notebook it find where all of them are

We have the need to do something We have the need to do something several times, but the number of times several times, but the number of times depends upon circumstances that vary.depends upon circumstances that vary.

The solution is the The solution is the while loopwhile loop; one of ; one of Java’s Java’s loop statementsloop statements

Page 10: Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.

The while loopThe while loop

A A while loopwhile loop is one way to perform a set of is one way to perform a set of actions repeatedly, without having to write those actions repeatedly, without having to write those actions more than once.actions more than once.

Here is a general formatHere is a general format

while ( loop condition )while ( loop condition )

{{

loop body //statements you want toloop body //statements you want to

//repeat//repeat

}}

Page 11: Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.

ExampleExample

/*/* ** List all notes in the notebookList all notes in the notebook */*/public void listNotes()public void listNotes(){{int index = 0;int index = 0;while ( index < notes.size() )while ( index < notes.size() ){{

System.out.println(notes.get(index));System.out.println(notes.get(index));index++;index++;

}}}}

Page 12: Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.

While vs. IfWhile vs. If

Do not confuse a while loop with an if.Do not confuse a while loop with an if. Although they look similar, they operate Although they look similar, they operate

in very different waysin very different ways The biggest difference is that once the The biggest difference is that once the

body of the loop has been executed for body of the loop has been executed for the first time, we go back to the test the first time, we go back to the test again to see if the body should be again to see if the body should be executed.executed.

Page 13: Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.

IteratorsIterators

Examining every item in a collection is a Examining every item in a collection is a very common activity.very common activity.

The ArrayList class supplies an iterator The ArrayList class supplies an iterator method that supplies an Iterator object method that supplies an Iterator object that allows us to iterate over the collectionthat allows us to iterate over the collection

We must add another import statement to We must add another import statement to use the iterator objectuse the iterator object import java.util.Iterator;import java.util.Iterator;

Page 14: Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.

IteratorsIterators

An Iterator supplies two methods to iterate An Iterator supplies two methods to iterate over a collection: hasNext and nextover a collection: hasNext and next

Iterator it = myCollection.iterator();Iterator it = myCollection.iterator();while ( it.hasNext() )while ( it.hasNext() ){{//call it.next() to get the //call it.next() to get the //next object and do //next object and do something //with that objectsomething //with that object

}}

Page 15: Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.

Indices vs. IteratorsIndices vs. Iterators

We have seen approaches to accessing We have seen approaches to accessing elements in an ArrayListelements in an ArrayList

In this example, both seem equally In this example, both seem equally adequateadequate

Java supplies many other collections that Java supplies many other collections that are not as straight forewordare not as straight foreword

It may also be inefficient or impossible to It may also be inefficient or impossible to access elements through indices.access elements through indices.

All Java collections have iteratorsAll Java collections have iterators

Page 16: Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.

The Auction System The Auction System ExampleExample

The Auction System ExampleThe Auction System Example highestBid == nullhighestBid == null nullnull is a Java key word and means ‘no is a Java key word and means ‘no

object’object’ When a field is an object type and it is When a field is an object type and it is

not explicity initialized in a constructor, not explicity initialized in a constructor, that field will contain the value nullthat field will contain the value null

Page 17: Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.

CastingCasting

Casting is an important feature of JavaCasting is an important feature of Java

Lot lot = (Lot) it.next();Lot lot = (Lot) it.next(); A cast consists of the name of a type written A cast consists of the name of a type written

alone between a pair of parenthesesalone between a pair of parentheses Casting is commonly seen when retrieving Casting is commonly seen when retrieving

objects from a collectionobjects from a collection This is required because collections can store This is required because collections can store

any type of objectany type of object Casting makes it clear what type of object it isCasting makes it clear what type of object it is

Page 18: Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.

Who? Anonymous ObjectWho? Anonymous Object

When you need to create an object to add to a When you need to create an object to add to a collectioncollection

You can create an anonymous object to take You can create an anonymous object to take care of thiscare of this

Lot furtherLot = new Lot furtherLot = new Lot( nextLotNumber, description);Lot( nextLotNumber, description);

lots.add(furtherLot);lots.add(furtherLot); ororlots.add(new Lot( nextLotNumber, lots.add(new Lot( nextLotNumber, description));description));

Page 19: Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.

Fixed-size CollectionsFixed-size Collections

When you do know the number of items When you do know the number of items to store at the time you write the to store at the time you write the program.program.

You can used a fixed-sized collectionYou can used a fixed-sized collection In Java the fixed-sized collection is called In Java the fixed-sized collection is called

an an ArrayArray

Page 20: Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.

ArraysArrays

Arrays are one of the oldest ways to Arrays are one of the oldest ways to store datastore data

They come with some special syntax to They come with some special syntax to access elements in the arrayaccess elements in the array

Another type of loop is often used to Another type of loop is often used to process elements in an array.process elements in an array.

Log Analyzer ProjectLog Analyzer Project

Page 21: Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.

Declaring Array VariablesDeclaring Array Variables

To declare a variable of an array typeTo declare a variable of an array type private int[ ] hourCounts;private int[ ] hourCounts; Notice the brackets [ ]Notice the brackets [ ]

Then to create the array object, you use Then to create the array object, you use new just like all other object creationsnew just like all other object creations hourCount = new int[24];hourCount = new int[24]; Notice the number between the bracketsNotice the number between the brackets

Page 22: Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.

Using Array ObjectsUsing Array Objects

You access individual array elements by You access individual array elements by indexingindexing into the array into the array

An index is a number between 0 and one An index is a number between 0 and one less then the number used to create the less then the number used to create the arrayarray labels[6]labels[6] machines[0]machines[0] people[x+10-y]people[x+10-y]

Page 23: Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.

IndicesIndices

You can use an array access anywhere You can use an array access anywhere you can use a variable of the same typeyou can use a variable of the same type labels[5] = “Quit”;labels[5] = “Quit”; double half = readings[0] / 2;double half = readings[0] / 2; System.out.println(people[3].getName());System.out.println(people[3].getName()); machines[0] = new TicketMachine(500);machines[0] = new TicketMachine(500);

Page 24: Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.

The for LoopThe for Loop

The for loop is an alternative choice to The for loop is an alternative choice to the while loopthe while loop

It is particularly appropriate whenIt is particularly appropriate when We wish to execute a set of commands a We wish to execute a set of commands a

fixed number of timesfixed number of times We need a variable inside the loop whose We need a variable inside the loop whose

value changes by a fixed amountvalue changes by a fixed amount

Page 25: Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.

The for Loop: An exampleThe for Loop: An example

for( int hour=0; for( int hour=0; hour<hourCounts.length; hour+hour<hourCounts.length; hour++)+)

{{System.out.println(hour + “: ” + System.out.println(hour + “: ” + hourCounts[hour]);hourCounts[hour]);

}}

Page 26: Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.

QuizQuiz

Write a class for a Person that will store a Write a class for a Person that will store a first name and a last name.first name and a last name.

You do not need to write any methods, You do not need to write any methods, just the private fields and the class just the private fields and the class wrapper.wrapper.