Post on 30-Nov-2015
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
Part I:Foundations of object
orientation
Grouping objects
MSc. Fernando A. Rojas Morales
3.0
3Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Main concepts to be covered
• Collections
• Loops
• Iterators
• Arrays
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.
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.
6Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
A personal notebook
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.
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;
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
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
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
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 );
}
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!
14
The ArrayList Class
• To store primitive types in an ArrayList, use the wrapper classes (Integer, Double, Character,
Boolean, etc.)
See Wrappers Example.
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 >() ;}
...}
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)
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”.
18Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Object structures with collections
19Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Adding a third note
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?
21Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
DRY and Delegation
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.
23Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Generic classes
24Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Index numbering
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.}
}
26Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Index numbering
27Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Removal may affect numbering
28Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Removal may affect numbering
29Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Processing a whole collection
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.
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
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
33Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
The for-each loop
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.
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
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
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.
38Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
The while loop
39Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
The while loop
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.
41Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Summary of the notebook example
42Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Summary of the notebook example
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.
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 );
45Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Anonymous Objects
46Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Anonymous Objects
47Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Anonymous Objects
48Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Using collections
49Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Using collections
50Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Using collections
51Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Using collections
52Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Using collections
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.
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.
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.
56Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
The weblog-analyzer project
57Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
The weblog-analyzer project
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
59Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
The hourCounts array
60Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Creating an array object
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]++;
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).
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.
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
}
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
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.
67Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
The for loop
68Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Analizador Web
69Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Analizador Web
70Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Analizador Web
71Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
72Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
73Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Review
74Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Review