Presentation is loading. Please wait.

Presentation is loading. Please wait.

4 Grouping objects (cont.)

Similar presentations


Presentation on theme: "4 Grouping objects (cont.)"— Presentation transcript:

1 4 Grouping objects (cont.)
Objektorienterad programmering d2 4 Grouping objects (cont.) Iteration Arrays BK chap , DAT050, 18/19, lp 1

2 Main concepts to be covered
Objektorienterad programmering d2 Main concepts to be covered Iteration with Loops Collection traversal with Iterators Fixed-size collections - Arrays Rep. F3 bild 30: ArrayList, MusicOrganizer Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

3 Objektorienterad programmering d2
Iteration We often want to perform some actions an arbitrary number of times. 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. We will start with its for-each loop. With collections, we often want to repeat things once for every object in a particular collection. Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

4 For-each loop pseudo code
Objektorienterad programmering d2 For-each loop pseudo code General form of the for-each loop for keyword loop header for(ElementType element : collection) { loop body } Statement(s) to be repeated Pseudo-code expression of the actions of a for-each loop For each element in collection, do the things in the loop body. Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

5 Objektorienterad programmering d2
A Java example /** * List all file names in the organizer. */ public void listAllFiles() { for(String filename : files) { System.out.println(filename); } for each filename in files, print out filename Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

6 Objektorienterad programmering d2
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. Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

7 Objektorienterad programmering d2
While loop pseudo code General form of a while loop while keyword boolean test while(loop condition) { loop body } Statements to be repeated Pseudo-code expression of the actions of a while loop while we wish to continue, do the things in the loop body Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

8 Objektorienterad programmering d2
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 while the value of index is less than the size of the collection, print the next file name, and then increment index Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

9 Using a non-generic list
Objektorienterad programmering d2 Using a non-generic list private ArrayList files; // ”Old” Java style // the list elements have type Object /** * List all file names in the organizer. */ public void listAllFiles() { int index = 0; while(index < files.size()) { String filename = (String)files.get(index); System.out.println(filename); index++; } type cast Object to String Elementen i en lista har typen Object (ung. void* i C) Det man stoppar in behåller sin egen typ N.B. This style is obsolete Don’t use it! Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

10 Objektorienterad programmering d2
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. Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

11 Searching a collection
Objektorienterad programmering d2 Searching a collection 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. Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

12 Objektorienterad programmering d2
Finishing a search How do we finish a search? Either there are no more items to check (failure): index >= files.size() Or the item has been found (success): found == true Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

13 Loop condition for searching
Objektorienterad programmering d2 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: !(index >= files.size() || found)  index < files.size() && !found while ( cond ) { statements; } // post condition: !cond Detta gäller inte om vi avbryter loopen på något annat sätt, t.ex. med break Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

14 Searching a collection using a boolean
Objektorienterad programmering d2 Searching a collection using a boolean 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). Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

15 Searching a collection using break
Objektorienterad programmering d2 Searching a collection using break 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, 18/19, lp 1 DAT050, 18/19, lp 1

16 Searching a collection using a smarter condition
Objektorienterad programmering d2 Searching a collection using a smarter condition 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(); Denna variant är att föredra Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

17 Don’t forget the simple cases!
Objektorienterad programmering d2 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: The body will be executed zero or more times. Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

18 Objektorienterad programmering d2 Iterators
Grouping objects Iterators DAT050, 18/19, lp 1

19 Iterator and iterator()
Objektorienterad programmering d2 Iterator and iterator() Collections have an iterator() method. iterator() returns an Iterator object. Iterator<E> has three methods: boolean hasNext() E next() void remove() DAT050, 18/19, lp 1

20 Moving away from String
Objektorienterad programmering d2 Moving away from String Our collection of String objects for music tracks is limited. No separate identification of artist, title, etc. A Track class with separate fields: artist title filename Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

21 Using an Iterator object
Objektorienterad programmering d2 Using an Iterator object Iterator<ElementType> it = myCollection.iterator(); while(it.hasNext()) { call it.next() to get the next object do something with that object } java.util.Iterator returns an Iterator object public void listAllFiles() { Iterator<Track> it = files.iterator(); while(it.hasNext()) { Track tk = it.next(); System.out.println(tk.getDetails()); } - Vad är vitsen med detta? - Iteratorer används för många olika datastrukturer - Med samma syntax! OBS. Glöm inte elementtypen! Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

22 Objektorienterad programmering d2
Iterator mechanics Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

23 Objektorienterad programmering d2
myList:List myList.iterator() :Element :Element :Element :Element :Iterator Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

24 Objektorienterad programmering d2
myList:List :Element :Element :Element :Element = iterator.next(); :Iterator :Iterator hasNext()? Element e Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

25 Objektorienterad programmering d2
myList:List :Element :Element :Element :Element :Iterator :Iterator hasNext()? next() Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

26 Objektorienterad programmering d2
myList:List :Element :Element :Element :Element :Iterator :Iterator hasNext()? next() Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

27 Objektorienterad programmering d2
myList:List :Element :Element :Element :Element :Iterator :Iterator hasNext()? next() Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

28 Objektorienterad programmering d2
myList:List :Element :Element :Element :Element :Iterator hasNext()? Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

29 Wrong use of Iterator object
Objektorienterad programmering d2 Wrong use of Iterator object Iterator<Integer> it = myCollection.iterator(); while(it.hasNext()) { if( it.next() > 0 ) { System.out.println(it.next()); } What’s wrong here? Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

30 Objektorienterad programmering d2
Correct use of Iterator object Iterator<Integer> it = myCollection.iterator(); while(it.hasNext()) { int element = it.next(); if( element > 0 ) { System.out.println(element); } Normally next() is called once in each iteration. Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

31 Objektorienterad programmering d2
side note a for each loop ... for (ElementType x : myCollection) { ... do something with x } ... is in principle automatically translated into an iterator loop by the compiler Iterator<ElementType> it = myCollection.iterator(); while(it.hasNext()) { ElementType x = it.next(); ... do something with x } Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

32 Removing from a collection
Objektorienterad programmering d2 Removing from a collection Iterator<Track> it = tracks.iterator(); while(it.hasNext()) { Track t = it.next(); String artist = t.getArtist(); if(artist.equals(artistToRemove)) { it.remove(); } Use the Iterator’s remove method. Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

33 Objektorienterad programmering d2
Index versus Iterator Ways to iterate over a collection: 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. Iterator object. Often used with collections where indexed access is not very efficient, or impossible. Use to remove from a collection. Iteration is an important programming pattern. Iteratorer är mer generella – man kan byta datastruktur och ändå behålla koden intakt. Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

34 Collections and primitive types
Objektorienterad programmering d2 Collections and primitive types 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). ArrayList<Integer> al = new ArrayList<Integer>(); int i = 123; al.add(new Integer(i)); i = (al.get(0)).intValue(); box an int Type Wrapper int Integer long Long short Short float Float double Double char Character boolean Boolean ... TAVLAN Rita en figur som visar mappningen mellan en int och en Integer unbox the Integer Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

35 Collections and primitive types
Objektorienterad programmering d2 Collections and primitive types Java 5 (and later versions) performs boxing and unboxing automatically! ArrayList<Integer> al = new ArrayList<Integer>(); int i = 123; al.add(i); // auto boxing i = files.get(0); // auto unboxing Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

36 Fixed-size collections
Objektorienterad programmering d2 Fixed-size collections 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 primitive-type values. Arrays use a special syntax. Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

37 The weblog-analyzer project
Objektorienterad programmering d2 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. Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

38 Creating an array object
Objektorienterad programmering d2 Creating an array object public class LogAnalyzer { private int[] hourCounts; private LogfileReader reader; public LogAnalyzer() hourCounts = new int[24]; reader = new LogfileReader(); } ... Array variable declaration Array object creation Man kan skriva int hourCounts[] också (som i C). Storleken kan beräknas dynamiskt: - fältstorleken är inte låst vid compile-time som i C. Ett fält är ett objekt! Div. standardfunktioner i java.util.Arrays (TAVLAN) Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

39 Objektorienterad programmering d2
The hourCounts array Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

40 Objektorienterad programmering d2
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, 18/19, lp 1 DAT050, 18/19, lp 1

41 Objektorienterad programmering d2
Standard array use private int[] hourCounts; private String[] names; ... hourCounts = new int[24]; hourcounts[i] = 0; hourcounts[i]++; System.out.println(hourcounts[i]); declaration creation use Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

42 Objektorienterad programmering d2
Array literals The size is inferred from the data. private int[] numbers = { 3, 15, 4, 5 }; declaration, creation and initialization Array literals in this form can only be used in declarations. Related uses require new: numbers = new int[] { 3, 15, 4, 5 }; Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

43 Objektorienterad programmering d2
Array length private int[] numbers = { 3, 15, 4, 5 }; int n = numbers.length; no brackets! NB: length is a field rather than a method! It cannot be changed – ‘fixed size’. Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

44 Objektorienterad programmering d2
Array utilities Initialization ElemType[] arr = {value1,value2,...} arr = new ElemType[]{value1,value2,...} Number of elements arr.length Asignment and copy Shallow copy: arr2 = arr1 // reference copy Deep copy (=cloning): arr2 = (ElemType[])arr1.clone() System.arraycopy(arr1,pos1,arr2,pos2,n) Comparison arr1 == arr // identity Arrays.equals(arr1,arr2) // equality See java.util.Arrays for more array utilities Arrays.equals(a1,a2) om a1 och a2 har samma typ och samma storlek (kapacitet) och elementen är parvis lika Arrays.equals(null,null) -> true Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

45 Array traversal with for-loops
Objektorienterad programmering d2 Array traversal with for-loops for loop version for(int hour = 0; hour < hourCounts.length; hour++) { System.out.println(hour + ": " + hourCounts[hour]); } for-each loop version int hour = 0; for(int count : hourCounts) { System.out.println(hour++ + ": " + count); } Med for-each kan man bara läsa av fält som innehåller enkla värden. styrvariabeln blir en kopia av fältelementen Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

46 Objektorienterad programmering d2
The auction project The auction project provides further illustration of collections and iteration. Examples of using null. Anonymous objects. Chaining method calls. Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

47 Objektorienterad programmering d2
The auction project Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

48 Objektorienterad programmering d2
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, 18/19, lp 1 DAT050, 18/19, lp 1

49 Objektorienterad programmering d2
Anonymous objects Objects are often created and handed on elsewhere immediately: Lot oneMoreLot = new Lot(…); lots.add(oneMoreLot); We don’t really need oneMoreLot: lots.add(new Lot(…)); Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

50 Objektorienterad programmering d2
Chaining method calls Methods often return objects. We often immediately call a method on the returned object. Bid bid = lot.getHighestBid(); Person bidder = bid.getBidder(); We can use the anonymous object concept and chain method calls: lot.getHighestBid().getBidder() Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

51 Objektorienterad programmering d2
Chaining method calls Each method in the chain is called on the object returned from the previous method call in the chain. 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, 18/19, lp 1 DAT050, 18/19, lp 1

52 Objektorienterad programmering d2
Review 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. Objektorienterad programmering, DAT050, DAI2, 18/19, lp 1 DAT050, 18/19, lp 1

53 Objektorienterad programmering d2
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, 18/19, lp 1 DAT050, 18/19, lp 1


Download ppt "4 Grouping objects (cont.)"

Similar presentations


Ads by Google