4 Grouping objects (cont.)

Slides:



Advertisements
Similar presentations
Grouping objects Iterators. Iterator and iterator() Collections have an iterator() method. This returns an Iterator object. Iterator has three methods:
Advertisements

Grouping objects Arrays and for loops. Fixed-size collections Sometimes the maximum collection size can be pre-determined. Programming languages usually.
1 Features of the collection It increases its capacity as necessary. It keeps a private count: –size() accessor. It keeps the objects in order. Details.
Grouping objects Introduction to collections 5.0.
Grouping Objects Arrays and for loops. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Fixed-Size Collections.
Using Collections. Review of Collections Using an ArrayList It increases its capacity as necessary. It keeps a private count ( size() accessor). It keeps.
Grouping Objects 3 Iterators, collections and the while loop.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Programming with Collections Collections in Java Using Arrays Week 9.
Repetition Statements repeat block of code until a condition is satisfied also called loops Java supports 3 kinds of loops: while statement – repeats a.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
Grouping Objects 2 Collections and the for-each loop Collections and the while loop.
PHYS 2020 Making Choices; Arrays. Arrays  An array is very much like a matrix.  In the C language, an array is a collection of variables, all of the.
Grouping objects Collections and iterators. 04/11/2004Lecture 4: Grouping Objects2 Main concepts to be covered Collections Loops Iterators Arrays.
Modul 3 Collections af objekter Arraylist Collections Objektorienteret design og Java. 4.0.
Programming with Collections Grouping & Looping - Collections and Iteration Week 7.
Grouping objects Collections and iterators. Main concepts to be covered Collections Loops Iterators.
REPETITION CITS1001. Scope of this lecture Repetition for loops while loops 2.
Chapter 11 Arrays Continued
Objects First With Java A Practical Introduction Using BlueJ Grouping objects Collections and iterators 2.0.
Grouping objects Arrays, Collections and Iterators 1.0.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
JAVA 0. HAFTA Algorithms FOURTH EDITION Robert Sedgewick and Kevin Wayne Princeton University.
Grouping objects Introduction to collections 5.0.
Grouping objects Collections and iterators Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main.
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.
Introduction to Java Java Translation Program Structure
JAVA COLLECTIONS M. TAIMOOR KHAN (ADAPTED FROM SWINBURNE NOTES)
Grouping objects Iterators. Iterator type Third variation to iterate over a collection Uses a while loop and Iterator object But NO integer index variable.
Objects First With Java A Practical Introduction Using BlueJ Grouping objects Collections and iterators 1.0.
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.
GROUPING OBJECTS CITS1001. Lecture outline The ArrayList collection Process all items: the for-each loop 2.
Grouping objects Arrays. 2 Fixed-size collections The maximum collection size may be pre-determined with an upper limit Array is an fixed-size collection.
Grouping objects Introduction to collections 5.0.
1 COS 260 DAY 7 Tony Gauvin. 2 Agenda Questions? 3 rd Mini quiz next class (September 28) –Chap 3 concepts Assignment 1 Corrected Assignment 2 posted.
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
Grouping objects Iterators, collections and the while loop Equality and Equality == and equals(…)
Fixed-sized collections Introduction to arrays 6.0.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Grouping objects Introduction to collections 6.0.
Functional Processing of Collections (Advanced) 6.0.
© 2004 Pearson Addison-Wesley. All rights reserved October 5, 2007 Arrays ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
Arrays Chapter 7.
1 © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. for-each PROS easy to use access to ALL items one-by-one ability to change the state.
for-each PROS CONS easy to use access to ALL items one-by-one
Objects First with Java CITS1001 week 4
9 Improving structure with inheritance
Objects First with Java CITS1001
Objects First with Java Introduction to collections
Fixed-sized collections
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
Chapter 7 Part 1 Edited by JJ Shepherd
Loop Structures.
Coding #1 if(!(index < 0 || index >= list.size( )-1))
COS 260 DAY 7 Tony Gauvin.
COS 260 DAY 9 Tony Gauvin.
Objects First with Java Introduction to collections
Arrays, For loop While loop Do while loop
Arrays versus ArrayList
COS 260 DAY 8 Tony Gauvin.
COS 260 DAY 8 Tony Gauvin.
Object Oriented Programming in java
Objects First with Java Introduction to collections
COS 260 DAY 11 Tony Gauvin.
Collections and iterators
Arrays October 6, 2006 ComS 207: Programming I (in Java)
Review: libraries and packages
Loops CGS3416 Spring 2019 Lecture 7.
Collections and iterators
Presentation transcript:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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 == arr2 // 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

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

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

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

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

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

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

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

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

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