Objektorienterad programmering d2
Main concepts to be covered • Iteration with Loops • Collection traversal with Iterators • Fixed-size collections - Arrays
4 Grouping objects (cont.) Iteration Arrays BK chap. 4.8-4.15, 7.1-7.6
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Iteration
Förel. 4
2
For-each loop pseudo code
• We often want to perform some actions an arbitrary number of times.
General form of the for-each loop for keyword
– E.g., print all the elements in a collection.
• Most programming languages include loop statements to make this possible. • Java has several sorts of loop statement.
loop header for(ElementType element : collection) { loop body }
Statement(s) to be repeated
– We will start with its for-each loop. Pseudo-code expression of the actions of a for-each loop
• With collections, we often want to repeat things once for every object in a particular collection. Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
For each element in collection, do the things in the loop body.
Förel. 4
3
A Java example
4
• 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.
for each filename in files, print out filename
DAT050, 16/17, lp 1
Förel. 4
The while loop
/** * List all file names in the organizer. */ public void listAllFiles() { for(String filename : files) { System.out.println(filename); } }
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Förel. 4
5
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Förel. 4
6
1
Objektorienterad programmering d2
While loop pseudo code
A Java example /** * List all file names in the organizer. */ public void listAllFiles() { int index = 0; while(index < files.size()) { String filename = files.get(index); System.out.println(filename); index++; } Increment index by 1 }
General form of a while loop while keyword boolean test while(loop condition) { Statements to be repeated loop body }
Pseudo-code expression of the actions of a while loop
while the value of index is less than the size of the collection, print the next file name, and then increment index
while we wish to continue, do the things in the loop body
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Förel. 4
7
Using a non-generic list
Förel. 4
10
Förel. 4
12
– easier to write. – safer: it is guaranteed to stop.
Förel. 4
• 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. 9
Searching a collection
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Finishing a search • How do we finish a search? • Either there are no more items to check (failure):
A fundamental activity. Applicable beyond collections. Necessarily indefinite. We must code for both success and failure - exhausted search. • Both must make the loop’s condition false. • The collection might be empty.
• • • •
DAT050, 16/17, lp 1
8
• for-each:
/** * List all file names in the organizer. */ type cast Object public void listAllFiles() to String { int index = 0; while(index < files.size()) { String filename = (String)files.get(index); System.out.println(filename); index++; } N.B. This style is obsolete } Don’t use it!
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Förel. 4
for-each versus while
private ArrayList files; // ”Old” Java style // the list elements have type Object
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
index >= files.size()
• Or the item has been found (success): found == true
Förel. 4
11
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
2
Objektorienterad programmering d2
Searching a collection using a boolean
Loop condition for searching • With a while loop we need to state the condition for continuing: • So the loop’s condition will be the opposite of that for finishing:
int index = 0; boolean found = false; while(index < files.size() && !found) { String filename = files.get(index); if(filename .contains(searchString)) { // We don't need to keep looking. found = true; } else { index++; } } // Either we found it (found is true), // or we searched the whole collection // (found is false).
!(index >= files.size() || found) index < files.size() && !found • while ( cond ) { statements; } // post condition: !cond Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Förel. 4
13
Searching a collection using break
Förel. 4
14
Searching a collection using a smarter condition
int index = 0; while(index < files.size()) { String filename = files.get(index); if(filename.contains(searchString)) { // We don't need to keep looking. break; } else { index++; } } // Either we found it: index < files.size() // or we searched the whole collection: // index == files.size();
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
int index = 0; while( index < files.size() && ! files.get(index).contains(searchString) ) index++; // Either we found it: index < files.size() // or we searched the whole collection: // index == files.size();
Förel. 4
15
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Förel. 4
16
Don’t forget the simple cases! • Does the search still work if the collection is empty? • Yes! The loop’s body won’t be entered in that case. • Important feature of while:
Grouping objects Iterators
– The body will be executed zero or more times.
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
DAT050, 16/17, lp 1
Förel. 4
17
3
Objektorienterad programmering d2
Iterator and iterator()
Moving away from String
• Collections have an iterator() method. • iterator() returns an Iterator object. • Iterator has three methods:
• Our collection of String objects for music tracks is limited. • No separate identification of artist, title, etc. • A Track class with separate fields:
– boolean hasNext() – E next() – void remove()
– artist – title – filename Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Förel. 4
20
Förel. 4
22
Using an Iterator object java.util.Iterator
returns an Iterator object
Iterator it = myCollection.iterator(); while(it.hasNext()) { call it.next() to get the next object do something with that object }
Iterator mechanics
public void listAllFiles() { Iterator it = files.iterator(); while(it.hasNext()) { Track tk = it.next(); System.out.println(tk.getDetails()); } } Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Förel. 4
myList:List
21
myList:List
myList.iterator()
:Element
:Element
:Element
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
:Element
:Element
:Iterator
:Element
:Element
:Element
:Iterator:Iterator
hasNext()?
✔
Element e = iterator.next(); Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
DAT050, 16/17, lp 1
Förel. 4
23
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Förel. 4
24
4
Objektorienterad programmering d2
myList:List
myList:List
:Element
:Element
:Iterator
:Element
:Element
:Element
:Element
:Iterator
:Element
:Iterator
✔
hasNext()?
:Element
:Iterator
✔
hasNext()?
next()
next()
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Förel. 4
25
myList:List
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Förel. 4
26
myList:List
:Element
:Element
:Element
:Element
:Element
:Iterator
hasNext()?
:Element
:Element
:Element
:Iterator
:Iterator
✔
hasNext()?
✗
next()
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Förel. 4
27
Wrong use of Iterator object
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Förel. 4
28
Correct use of Iterator object
Iterator it = myCollection.iterator(); while(it.hasNext()) { if( it.next() > 0 ) { System.out.println(it.next()); } }
Iterator it = myCollection.iterator(); while(it.hasNext()) { int element = it.next(); if( element > 0 ) { System.out.println(element); } }
What’s wrong here? Normally next() is called once in each iteration.
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
DAT050, 16/17, lp 1
Förel. 4
29
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Förel. 4
30
5
Objektorienterad programmering d2
side note
Removing from a collection
a for each loop ... for (ElementType x : myCollection) { ... do something with x ... }
Iterator it = tracks.iterator(); while(it.hasNext()) { Track t = it.next(); String artist = t.getArtist(); if(artist.equals(artistToRemove)) { it.remove(); } }
... is in principle automatically translated into an iterator loop by the compiler Iterator it = myCollection.iterator(); while(it.hasNext()) { ElementType x = it.next(); ... do something with x ... } Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Förel. 4
Use the Iterator’s remove method.
31
– for-each loop. • Use if we want to process every element.
– while loop. • Use if we might want to stop part way through. • Use for repetition that doesn't involve a collection.
ArrayList al = new ArrayList();
– Iterator object.
int i = 123;
• Use if we might want to stop part way through. • Often used with collections where indexed access is not very efficient, or impossible. • Use to remove from a collection.
Förel. 4
i = (al.get(0)).intValue();
unbox the Integer 33
Collections and primitive types
int i = 123;
// auto unboxing
DAT050, 16/17, lp 1
Förel. 4
Wrapper
int long short float double char boolean ...
Integer Long Short Float Double Character Boolean
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Förel. 4
34
• Sometimes the maximum collection size can be pre-determined. • A special fixed-size collection type is available: an array. • Unlike the flexible List collections, arrays can store object references or primitivetype values. • Arrays use a special syntax.
ArrayList al = new ArrayList();
i = files.get(0);
Type
Fixed-size collections
• Java 5 (and later versions) performs boxing and unboxing automatically!
// auto boxing
box an int
al.add(new Integer(i));
• Iteration is an important programming pattern.
al.add(i);
32
• Java collections such as ArrayList can only store object types – not primitive types. • Each primitive type has a corresponding wrapper class that stores a primitive value as an object (Boxing).
• Ways to iterate over a collection:
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Förel. 4
Collections and primitive types
Index versus Iterator
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
35
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Förel. 4
36
6
Objektorienterad programmering d2
The weblog-analyzer project
Creating an array object
• Web server records details of each access. • Supports webmaster’s tasks. – – – –
public class LogAnalyzer { private int[] hourCounts; private LogfileReader reader;
Most popular pages. Busiest periods. How much data is being delivered. Broken references.
Array variable declaration
public LogAnalyzer() Array object creation { hourCounts = new int[24]; reader = new LogfileReader(); } ...
• Analyze accesses by hour.
}
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Förel. 4
37
The hourCounts array
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Förel. 4
38
Using an array • Square-bracket notation is used to access an array element: hourCounts[...] • Elements are used like ordinary variables. – As target of an assignment: • hourCounts[hour] = ...;
– In an expression: • adjusted = hourCounts[hour] – 3; • hourCounts[hour]++;
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Förel. 4
39
Standard array use private int[] hourCounts; private String[] names;
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
• The size is inferred from the data.
declaration
private int[] numbers = { 3, 15, 4, 5 };
numbers = new int[] { 3, 15, 4, 5 };
hourcounts[i] = 0; use hourcounts[i]++; System.out.println(hourcounts[i]);
DAT050, 16/17, lp 1
declaration, creation and initialization
• Array literals in this form can only be used in declarations. • Related uses require new:
creation
...
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
40
Array literals
... hourCounts = new int[24];
Förel. 4
Förel. 4
41
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Förel. 4
42
7
Objektorienterad programmering d2
Array utilities
Array length
• Initialization ElemType[] arr = {value1,value2,...} arr = new ElemType[]{value1,value2,...}
private int[] numbers = { 3, 15, 4, 5 };
• Number of elements
int n = numbers.length;
• Asignment and copy
arr.length
– Shallow copy:
no brackets!
arr2 = arr1 // reference copy
– Deep copy (=cloning):
• NB: length is a field rather than a method! • It cannot be changed – ‘fixed size’.
arr2 = (ElemType[])arr1.clone() System.arraycopy(arr1,pos1,arr2,pos2,n)
• Comparison arr1 == arr2 // identity Arrays.equals(arr1,arr2) // equality See java.util.Arrays for more array utilities
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Förel. 4
43
Array traversal with for-loops
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Förel. 4
44
The auction project
for loop version for(int hour = 0; hour < hourCounts.length; hour++) { System.out.println(hour + ": " + hourCounts[hour]); }
for-each loop version
• The auction project provides further illustration of collections and iteration. • Examples of using null. • Anonymous objects. • Chaining method calls.
int hour = 0; for(int count : hourCounts) { System.out.println(hour++ + ": " + count); }
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Förel. 4
45
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
The auction project
Förel. 4
46
null • Used with object types. • Used to indicate, 'no object'. • We can test if an object variable holds the null value: if (highestBid == null) ... • Used to indicate ‘no bid yet’.
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
DAT050, 16/17, lp 1
Förel. 4
47
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Förel. 4
48
8
Objektorienterad programmering d2
Anonymous objects
Chaining method calls
• Objects are often created and handed on elsewhere immediately:
• Methods often return objects. • We often immediately call a method on the returned object.
Lot oneMoreLot = new Lot(…); lots.add(oneMoreLot);
Bid bid = lot.getHighestBid(); Person bidder = bid.getBidder();
• We can use the anonymous object concept and chain method calls:
• We don’t really need oneMoreLot: lots.add(new Lot(…)); Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
lot.getHighestBid().getBidder() Förel. 4
49
Chaining method calls
Förel. 4
50
Review
• Each method in the chain is called on the object returned from the previous method call in the chain.
• Loop statements allow a block of statements to be repeated. • The for-each loop allows iteration over a whole collection. • The while loop allows the repetition to be controlled by a boolean expression. • All collection classes provide special Iterator objects that provide sequential access to a whole collection.
String name = lot.getHighestBid().getBidder().getName(); Returns a Bid object from the Lot Returns a Person object from the Bid Returns a String object from the Person Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Förel. 4
51
Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
Förel. 4
52
Review • Arrays are appropriate where a fixed-size collection is required. • Arrays use special syntax. • For loops are used when an index variable is required. • For loops offer an alternative to while loops when the number of repetitions is known. Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1
DAT050, 16/17, lp 1
Förel. 4
53
9