74
El Señor le dijo a Abram: …“¡por medio de ti serán bendecidas todas las familias de la tierra!”. [Génesis 3:3 – La Bíblia] 3.0

Pp04.Grouping Objects

Embed Size (px)

Citation preview

Page 1: Pp04.Grouping Objects

El Señor le dijo a Abram: …“¡por medio de ti serán

bendecidas todas las familias de la tierra!”.

[Génesis 3:3 – La Bíblia]

3.0

Page 2: Pp04.Grouping Objects

Part I:Foundations of object

orientation

Grouping objects

MSc. Fernando A. Rojas Morales

3.0

Page 3: Pp04.Grouping Objects

3Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Main concepts to be covered

• Collections

• Loops

• Iterators

• Arrays

Page 4: Pp04.Grouping Objects

4Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

The requirement to group objects

• Many applications involve collections of objects:

– Personal organizers.

– Library catalogs.

– Student-record system.

• The number of items to be stored varies.

– Items added.

– Items deleted.

Page 5: Pp04.Grouping Objects

5Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

A personal notebook

• Notes may be stored.

• Individual notes can be viewed.

• There is no limit to the number of notes.

• It will tell how many notes are stored.

Page 6: Pp04.Grouping Objects

6Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

A personal notebook

Page 7: Pp04.Grouping Objects

7Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

A first look at libraries class

• The collections of objects are objects that can store an arbitrary number of objects.

• Grouping objects is a recurring requirement.– The java.util package contains

classes for doing this.

Page 8: Pp04.Grouping Objects

8

Declaring an ArrayList

Use this syntax:ArrayList<E> arrayListName;

E is a class name that specifies the type of object references that will be stored in the ArrayList.

Example:ArrayList< String > listOfStrings;

ArrayList< Auto > listOfCars;

ArrayList< Integer > listOfInts;

Page 9: Pp04.Grouping Objects

9

ArrayList Constructors

• The capacityof an ArrayList is the total number of elements allocated to the list.

• The sizeof an anArrayList is the number of elements that are used.

Constructor name and argument listArrayList<E>

constructs an ArrayList object of type E with an initial capacity of 10ArrayList<E>( int initialCapacity )

constructs an ArrayList object of type E with the specified initial capacity

Page 10: Pp04.Grouping Objects

10

ArrayList Methods

Return value Method name and argument listboolean add( E element )

appends element to the end of the listvoid clear( )

removes all the elements in the listint size( )

returns the number of elements in the listE remove( int index )

removes the element at the specified indexposition

Page 11: Pp04.Grouping Objects

11

More ArrayList Methods

Return value Method name and argument listE get( int index )

returns the element at the specified indexposition; the element is not removed from the list.

E set( int index, E element )

replaces the element at the specified indexposition with the specified element

void trimToSize( )

sets the capacity of the list to its current size

Page 12: Pp04.Grouping Objects

12

The Enhanced for Loop• Simplifies processing of lists

• The standard form is:for ( ClassName currentObject : arrayListName )

{

// process currentObject

}

• This enhanced for loop prints all elements of an ArrayList of Strings named list:

for ( String s : list )

{

System.out.println( s );

}

Page 13: Pp04.Grouping Objects

13

Using an ArrayList

We want to write a program for a bookstore that allows users to search for books using keywords.

We will have three classes in this program:– A Book class, with instance variables representing the title,

author, and price

– A BookStore class that stores Book objects in an ArrayList

and provides a searchForTitle method

– A BookSearchEngine class, which provides the user interface and the main method

Exercice: Do it now!

Page 14: Pp04.Grouping Objects

14

The ArrayList Class

• To store primitive types in an ArrayList, use the wrapper classes (Integer, Double, Character,

Boolean, etc.)

See Wrappers Example.

Page 15: Pp04.Grouping Objects

15Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

import java.util.ArrayList;

/*** ...*/

public class Notebook{

// Storage for an arbitrary number of notes.private ArrayList< String > notes;

/*** Perform any initialization required for the* notebook.*/

public Notebook(){

notes = new ArrayList< String >() ;}

...}

Page 16: Pp04.Grouping Objects

16Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Using the collectionpublic class Notebook{

private ArrayList<String> notes;...

public void storeNote( String note ){

notes. add ( note );}

public int numberOfNotes(){

return notes. size ();}

...}

Adding a new note

Returning the number of notes(delegation)

Page 17: Pp04.Grouping Objects

17Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Collections

• We specify:

– the type of collection: ArrayList

– the type of objects it will contain: < String >

• We say, “ArrayList of String”.

Page 18: Pp04.Grouping Objects

18Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Object structures with collections

Page 19: Pp04.Grouping Objects

19Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Adding a third note

Page 20: Pp04.Grouping Objects

20Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Features of the collection

• It increases its capacity as necessary.

• It keeps a private count (size()accessor).

• It keeps the objects in order.

• Details of how all this is done are hidden.

– Does that matter? Does not knowing how prevent us from using it?

Page 21: Pp04.Grouping Objects

21Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

DRY and Delegation

Page 22: Pp04.Grouping Objects

22Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Generic classes

• Collections are known as parameterized or generic types.

• ArrayList implements list functionality:

– add , get , size , etc.

• The type parameter says what we want a list of:– ArrayList< Person >

– ArrayList< String >

– ArrayList< TicketMachine >

– etc.

Page 23: Pp04.Grouping Objects

23Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Generic classes

Page 24: Pp04.Grouping Objects

24Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Index numbering

Page 25: Pp04.Grouping Objects

25Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Retrieving an objectIndex validity checks

Retrieve and print the note

public void showNote( int noteNumber ){

if( noteNumber < 0 ) {

// This is not a valid note number.}else if( noteNumber < numberOfNotes() ) {

System.out.println( notes.get( noteNumber ) );}else {

// This is not a valid note number.}

}

Page 26: Pp04.Grouping Objects

26Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Index numbering

Page 27: Pp04.Grouping Objects

27Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Removal may affect numbering

Page 28: Pp04.Grouping Objects

28Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Removal may affect numbering

Page 29: Pp04.Grouping Objects

29Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Processing a whole collection

Page 30: Pp04.Grouping Objects

30Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Iteration

• We often want to perform some actions an arbitrary number of times.• e.g., print all the notes in the notebook. How

many are there?

• Most programming languages include loop statements to make this possible.

• Java has several sorts of loop statement.

Page 31: Pp04.Grouping Objects

31Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

For-each loop pseudo code

for( ElementType element : collection ){

loop body}

For each element in collection, do the things in the loop body.

loop headerfor keyword

Statement(s) to be repeated

Pseudo-code expression of the actions of a for-each loop

General form of the for-each loop

Page 32: Pp04.Grouping Objects

32Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

A Java example

/*** List all notes in the notebook.*/

public void listNotes(){

for( String note : notes ) {

System.out.println( note );}

}

for each note in notes, print out note

Page 33: Pp04.Grouping Objects

33Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

The for-each loop

Page 34: Pp04.Grouping Objects

34Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

The while loop

• A for-each loop repeats the loop body for each object in a collection.

• Sometimes we require more variation than this.

• We can use a boolean condition to decide whether or not to keep going.

• A while loop provides this control.

Page 35: Pp04.Grouping Objects

35Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

While loop pseudo code

while( loop condition ){

loop body}

while we wish to continue, do the things in the loop body

boolean test

while keyword

Statements to be repeated

Pseudo-code expression of the actions of a while loop

General form of a while loop

Page 36: Pp04.Grouping Objects

36Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

/*** List all notes in the notebook.*/

public void listNotes(){

int index = 0;while( index < notes.size() ) {

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

}}

A Java example

Increment index by 1

while the value of index is less than the size of

the collection, print the next note, and then

increment index

Page 37: Pp04.Grouping Objects

37Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Searching in a collection

int index = 0;boolean found = false;while( index < notes.size() && !found ) {

String note = notes.get( index );if( note.contains( searchString ) ) {

// We don't need to keep looking.found = true;

}else {

index++;}

}// Either we found it, or we searched the whole// collection.

Page 38: Pp04.Grouping Objects

38Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

The while loop

Page 39: Pp04.Grouping Objects

39Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

The while loop

Page 40: Pp04.Grouping Objects

40Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

for-each versus while

• for-each:– easier to write.

– safer: it is guaranteed to stop.

• while:– we don’t have to process the whole

collection.

– doesn’t even have to be used with a collection.

– take care: could be an infinite loop.

Page 41: Pp04.Grouping Objects

41Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Summary of the notebook example

Page 42: Pp04.Grouping Objects

42Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Summary of the notebook example

Page 43: Pp04.Grouping Objects

43Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

The auction project

• The auction project provides further illustration of collections and iteration.

• One further point to follow up: the null value.

– Used to indicate, 'no object'.

– We can test if an object variable holds the null variable.

Page 44: Pp04.Grouping Objects

44Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

The auction project (interesting lines of code 1)

// from Lot classif( ( highestBid == null ) ||// from Auction classlots.add ( new Lot( nextLotNumber ,

description ) );

• Objeto anonimo equivalente a:Lot newLot = new lot( nextLotNumber ,

description);lots.add ( newLot );

Page 45: Pp04.Grouping Objects

45Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Anonymous Objects

Page 46: Pp04.Grouping Objects

46Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Anonymous Objects

Page 47: Pp04.Grouping Objects

47Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Anonymous Objects

Page 48: Pp04.Grouping Objects

48Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Using collections

Page 49: Pp04.Grouping Objects

49Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Using collections

Page 50: Pp04.Grouping Objects

50Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Using collections

Page 51: Pp04.Grouping Objects

51Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Using collections

Page 52: Pp04.Grouping Objects

52Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Using collections

Page 53: Pp04.Grouping Objects

53Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Fixed-size collections

• Sometimes the maximum collection size can be pre-determined.

• Programming languages usually offer a special fixed-size collection type: an array.

• Java arrays can store objects or primitive-type values. Flexible-size collections can only store objects.

Page 54: Pp04.Grouping Objects

54Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Fixed-size collections

• Access to the items held in an array is often more efficient than access to the items in a comparable flexible-size collection.

• Arrays use a special syntax.

Page 55: Pp04.Grouping Objects

55Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

The weblog-analyzer project

• Web server records details of each access.

• Supports webmaster’s tasks.– Most popular pages.

– Busiest periods.

– How much data is being delivered.

– Broken references.

• Analyze accesses by hour.

Page 56: Pp04.Grouping Objects

56Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

The weblog-analyzer project

Page 57: Pp04.Grouping Objects

57Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

The weblog-analyzer project

Page 58: Pp04.Grouping Objects

58Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Creating an array object

public class LogAnalyzer{

private int[] hourCounts ;private LogfileReader reader;

public LogAnalyzer(){

hourCounts = new int[24] ;reader = new LogfileReader();

}...

}

Array object creation

Array variable declaration

Page 59: Pp04.Grouping Objects

59Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

The hourCounts array

Page 60: Pp04.Grouping Objects

60Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Creating an array object

Page 61: Pp04.Grouping Objects

61Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Using an array

• Square-bracket notation is used to access an array element: hourCounts[...]

• Elements are used like ordinary variables.

– On the left of an assignment:• hourCounts[hour] = ...;

– In an expression:• adjusted = hourCounts[hour] – 3;

• hourCounts[hour]++;

Page 62: Pp04.Grouping Objects

62Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Using an array

• Here are some examples that use array expressions in different places:labels[5] = "Quit";double half = readings[0] / 2;System.out.println( people[3].getName() );machines[0] = new TicketMachine( 500 );

• An array index on the left hand side is equivalent of a mutator (or set method). Using one anywhere else represents the equivalent of an accessor (or getmethod).

Page 63: Pp04.Grouping Objects

63Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

The for loop

• There are two variations of the for loop, for-each and for.

• The for loop is often used to iterate a fixed number of times.

• Often used with a variable that changes a fixed amount on each iteration.

Page 64: Pp04.Grouping Objects

64Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

For loop pseudo-code

for( initialization; condition; post-body action) {statements to be repeated

}

General form of a for loop

Equivalent in while-loop form

initialization;while( condition) {

statements to be repeatedpost-body action

}

Page 65: Pp04.Grouping Objects

65Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

A Java example

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

System.out.println(hour + ": " + hourCounts[hour]);}

int hour = 0;while( hour < hourCounts.length ) {

System.out.println(hour + ": " + hourCounts[hour]);hour++ ;

}

for loop version

while loop version

Page 66: Pp04.Grouping Objects

66Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

A Java example

• All arrays contain a field length that contains the value of the fixed size of that array.

• The condition uses the less-than operator, '<', to check the value of hour against the length of the array.

Page 67: Pp04.Grouping Objects

67Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

The for loop

Page 68: Pp04.Grouping Objects

68Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Analizador Web

Page 69: Pp04.Grouping Objects

69Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Analizador Web

Page 70: Pp04.Grouping Objects

70Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Analizador Web

Page 71: Pp04.Grouping Objects

71Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 72: Pp04.Grouping Objects

72Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 73: Pp04.Grouping Objects

73Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Review

Page 74: Pp04.Grouping Objects

74Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Review