Grouping objects Collections and iterators 3.0. 2 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main.

Slides:



Advertisements
Similar presentations
Why not just use Arrays? Java ArrayLists.
Advertisements

Grouping objects Iterators. Iterator and iterator() Collections have an iterator() method. This returns an Iterator object. Iterator has three methods:
Grouping objects Arrays and for loops. Fixed-size collections Sometimes the maximum collection size can be pre-determined. Programming languages usually.
Collections & Loops Chapter 5 Copyright © 2012 Pearson Education, Inc.
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.
Programming with Collections Collections in Java Using Arrays Week 9.
More sophisticated behavior Using library classes to implement some more advanced functionality 4.0.
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.
Grouping Objects 1 Introduction to Collections.
Grouping objects Collections and iterators. 04/11/2004Lecture 4: Grouping Objects2 Main concepts to be covered Collections Loops Iterators Arrays.
Understanding class definitions – Part II –. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main.
More sophisticated behavior Using library classes to implement some more advanced functionality 3.0.
Modul 3 Collections af objekter Arraylist Collections Objektorienteret design og Java. 4.0.
Programming with Collections Grouping & Looping - Collections and Iteration Week 7.
Random, Collections & Loops Chapter 5 Copyright © 2012 Pearson Education, Inc.
Grouping objects Collections and iterators. Main concepts to be covered Collections Loops Iterators.
Invitation to Computer Science, Java Version, Second Edition.
REPETITION CITS1001. Scope of this lecture Repetition for loops while loops 2.
Objects First With Java A Practical Introduction Using BlueJ Grouping objects Collections and iterators 2.0.
Grouping objects Arrays, Collections and Iterators 1.0.
Grouping objects Introduction to collections 5.0.
1 CSC 221: Computer Programming I Fall 2004 Lists, data access, and searching  ArrayList class  ArrayList methods: add, get, size, remove  example:
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.
JAVA COLLECTIONS M. TAIMOOR KHAN (ADAPTED FROM SWINBURNE NOTES)
Understanding class definitions
Objects First With Java A Practical Introduction Using BlueJ Supplementary Material for Java
OOP (Java): Grouping/ OOP (Java) Objectives – –discuss call-by-value and call-by-reference, arrays, collections, and iterators Semester.
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.
Programming Fundamentals 2: Grouping/ F II Objectives – –discuss call-by-value and call-by-reference, arrays, collections, and iterators.
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.
1 COS 260 DAY 9 Tony Gauvin. 2 Agenda Questions? 3 rd Mini quiz –Good results ->All A’s –Threw out question on name overloading 4 th Mini quiz next class.
Collections and Iteration Week 13.  Collections  ArrayList objects  Using loops with collections Collections and Iteration CONCEPTS COVERED THIS WEEK.
Grouping objects Iterators, collections and the while loop Equality and Equality == and equals(…)
Fixed-sized collections Introduction to arrays 6.0.
Grouping objects Introduction to collections 6.0.
CONDITIONALS CITS1001. Scope of this lecture if statements switch statements Source ppts: Objects First with Java - A Practical Introduction using BlueJ,
Functional Processing of Collections (Advanced) 6.0.
Coming up ArrayList ArrayList vs Array – Declaration – Insertion – Access – Removal Wrapper classes Iterator object.
Chapter 8: Understanding Collections Textbook: Chapter 4.
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
Objects First with Java CITS1001
Objects First with Java Introduction to collections
Fixed-sized collections
Loop Structures.
COS 260 DAY 7 Tony Gauvin.
Functional Processing of Collections (Advanced)
COS 260 DAY 9 Tony Gauvin.
Objects First with Java Introduction to collections
COS 260 DAY 10 Tony Gauvin.
COS 260 DAY 8 Tony Gauvin.
COS 260 DAY 8 Tony Gauvin.
Object Oriented Programming in java
Objects First with Java Introduction to collections
F II 5. Grouping Objects Objectives
Understanding class definitions
COS 260 DAY 11 Tony Gauvin.
Collections and iterators
Collections and iterators
Presentation transcript:

Grouping objects Collections and iterators 3.0

2 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main concepts to be covered Collections Loops Iterators Arrays

3 Objects 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.

4 Objects 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. Explore the notebook1 project.

5 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Class libraries Collections of useful classes. We don’t have to write everything from scratch. Java calls its libraries, packages. Grouping objects is a recurring requirement. –The java.util package contains classes for doing this.

6 Objects 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 notes; /** * Perform any initialization required for the * notebook. */ public Notebook() { notes = new ArrayList (); }... }

7 Objects 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: We say, “ArrayList of String”.

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

9 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Adding a third note

10 Objects 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?

11 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Using the collection public class Notebook { private ArrayList 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)

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

13 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Retrieving an object Index 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. }

14 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Removal may affect numbering

15 Objects 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 –etc.

16 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Review Collections allow an arbitrary number of objects to be stored. Class libraries usually contain tried- and-tested collection classes. Java’s class libraries are called packages. We have used the ArrayList class from the java.util package.

17 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Review Items may be added and removed. Each item has an index. Index values may change if items are removed (or further items added). The main ArrayList methods are add, get, remove and size. ArrayList is a parameterized or generic type.

18 Objects 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. –We will start with its for-each loop.

19 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Iteration fundamentals We often want to repeat some actions over and over. Loops provide us with a way to control how many times we repeat those actions. With collections, we often want to repeat things once for every object in a particular collection.

20 Objects 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 header for keyword Statement(s) to be repeated Pseudo-code expression of the actions of a for-each loop General form of the for-each loop

21 Objects 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

22 Objects 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.

23 Objects 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

24 Objects 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

25 Objects 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.

26 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling While without a collection // Print all even numbers from 0 to 30. int index = 0; while(index <= 30) { System.out.println(index); index = index + 2; }

27 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Searching 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.

28 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Using an Iterator object Iterator 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 listNotes() { Iterator it = notes.iterator(); while(it.hasNext()) { System.out.println(it.next()); }

29 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 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. Use if we might want to stop part way through. Often used with collections where indexed access is not very efficient, or impossible. Iteration is an important programming pattern.

30 Objects 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.

31 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 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.

32 Objects 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. Arrays use a special syntax.

33 Objects 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.

34 Objects 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

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

36 Objects 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]++;

37 Objects 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.

38 Objects 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 repeated post-body action }

39 Objects 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

40 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling for loop with bigger step // Print multiples of 3 that are below 40. for(int num = 3; num < 40; num = num + 3) { System.out.println(num); }

41 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Review Arrays are appropriate where a fixed- size collection is required. Arrays use special syntax. For loops offer an alternative to while loops when the number of repetitions is known. For loops are used when an index variable is required.