Grouping objects Collections and iterators. 04/11/2004Lecture 4: Grouping Objects2 Main concepts to be covered Collections Loops Iterators Arrays.

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.
Loops – While, Do, For Repetition Statements Introduction to Arrays
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
Grouping Objects 2 Collections and the for-each loop Collections and the while loop.
Grouping Objects 1 Introduction to Collections.
Modul 3 Collections af objekter Arraylist Collections Objektorienteret design og Java. 4.0.
Programming with Collections Grouping & Looping - Collections and Iteration Week 7.
ArrayLists.  The Java API includes a class named ArrayList. The introduction to the ArrayList class in the Java API documentation is shown below.  java.lang.Object.
Random, Collections & Loops Chapter 5 Copyright © 2012 Pearson Education, Inc.
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.
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:
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.
JAVA COLLECTIONS M. TAIMOOR KHAN (ADAPTED FROM SWINBURNE NOTES)
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.
Chapter 5 – Part 3 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 Outline The if Statement and Conditions Other Conditional.
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.
Comparing ArrayLists and Arrays. ArrayLists ArrayLists are one type of flexible-size collection classes supported by Java –ArrayLists increase and decrease.
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(…)
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
Chapter 5 – Part 3 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/19 Outline The if Statement and Conditions Other Conditional.
Fixed-sized collections Introduction to arrays 6.0.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Grouping objects Introduction to collections 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:
Coming up ArrayList ArrayList vs Array – Declaration – Insertion – Access – Removal Wrapper classes Iterator object.
Chapter 8: Understanding Collections Textbook: Chapter 4.
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.
COS 260 DAY 9 Tony Gauvin.
Objects First with Java Introduction to collections
COS 260 DAY 8 Tony Gauvin.
COS 260 DAY 8 Tony Gauvin.
Arrays and Collections
Object Oriented Programming in java
Objects First with Java Introduction to collections
F II 5. Grouping Objects Objectives
COS 260 DAY 11 Tony Gauvin.
Collections and iterators
Arrays October 6, 2006 ComS 207: Programming I (in Java)
Review: libraries and packages
Collections and iterators
Arrays.
Presentation transcript:

Grouping objects Collections and iterators

04/11/2004Lecture 4: Grouping Objects2 Main concepts to be covered Collections Loops Iterators Arrays

04/11/2004Lecture 4: Grouping Objects3 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.

04/11/2004Lecture 4: Grouping Objects4 A personal notebook Notes may be stored. Individual notes can be viewed. There is no limit to the number of notes. It will tell you how many notes are stored.

04/11/2004Lecture 4: Grouping Objects5 A personal notebook

04/11/2004Lecture 4: Grouping Objects6 Class Libraries Learning to program is to learn how to reuse code written by other. There is no point in reinventing the wheel. Java comes with a library of useful classes, which are referred to as the Java API They are organized in packages that follow a directory structure

04/11/2004Lecture 4: Grouping Objects7 Class Libraries

04/11/2004Lecture 4: Grouping Objects8 Class libraries You can access the classes from your code, using the import statement import java.util.Vector; import java.util.*; Grouping objects is a recurring requirement. The java.util package contains classes for doing this. We will use ArrayList as a first example

04/11/2004Lecture 4: Grouping Objects9 Class Libraries

04/11/2004Lecture 4: Grouping Objects10 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(); }... }

04/11/2004Lecture 4: Grouping Objects11 Object structures with collections

04/11/2004Lecture 4: Grouping Objects12 Adding a third note

04/11/2004Lecture 4: Grouping Objects13 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?

04/11/2004Lecture 4: Grouping Objects14 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).

04/11/2004Lecture 4: Grouping Objects15 Index numbering

04/11/2004Lecture 4: Grouping Objects16 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. }

04/11/2004Lecture 4: Grouping Objects17 Removing an item public void removeNote(int noteNumber) { if(noteNumber < 0) { // This is not a valid note number, so do nothing. } else if(noteNumber < numberOfNotes()) { // This is a valid note number. notes.remove(noteNumber); } else { // This is not a valid note number, so do nothing. }

04/11/2004Lecture 4: Grouping Objects18 Removal may affect numbering

04/11/2004Lecture 4: Grouping Objects19 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.

04/11/2004Lecture 4: Grouping Objects20 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.

04/11/2004Lecture 4: Grouping Objects21 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 three sorts of loop statements. We will focus on its while loop to begin with.

04/11/2004Lecture 4: Grouping Objects22 While loop pseudo code while(loop condition) { loop body } while(there is at least one more note to be printed) { show the next note } Boolean test while keyword Statements to be repeated Pseudo-code example to print every note General form of a while loop

04/11/2004Lecture 4: Grouping Objects23 A Java example /** * List all notes in the notebook. */ public void listNotes() { int index = 0; while(index < notes.size()) { System.out.println(notes.get(index)); index++; } Increment by one

04/11/2004Lecture 4: Grouping Objects24 Increments i++ : the value of i is used first before it is being incremented with one a = 5; b = a++; a == 6; b == 5; ++i: increments i with one, the new value of i is then used. a = 5; b = ++a; a == 6; b == 6;

04/11/2004Lecture 4: Grouping Objects25 Iterating over a collection 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()); }

04/11/2004Lecture 4: Grouping Objects26 Iterators An iterator is an object that provides functionality to iterate over all elements of a collection or container class java.util.Iterator two main methods: hasNext() to check if the Iterator has more elements and next() to take the next object from the Iterator. You can access an iterator for all java collections. Not all collections can be accessed using indexes.

04/11/2004Lecture 4: Grouping Objects27 The auction project The auction project provides further illustration of collections and iteration. Two further points to follow up: The null value. Casting. Used to store the result of get into a variable: String message = (String) notes.get(0);

04/11/2004Lecture 4: Grouping Objects28 The auction project

04/11/2004Lecture 4: Grouping Objects29 The Lot Class public void bidFor(Person bidder, long value) { if((highestBid == null) || (highestBid.getValue() < value)) { // This bid is the best so far. setHighestBid(new Bid(bidder, value)); } else { System.out.println("Lot number: " + getNumber() + " (" + getDescription() + ")" + " already has a bid of: " + highestBid.getValue()); }

04/11/2004Lecture 4: Grouping Objects30 The null Keyword highestBid == null; The Java keyword null is used to mean ‘no object’ when a variable is not currently holding a reference to a particular object. setHighestBid(new Bid(bidder, value)); two things are done here: we create a new object Bid we pass this new object immediately to the method

04/11/2004Lecture 4: Grouping Objects31 The Auction Class public void showLots() { Iterator it = lots.iterator(); while(it.hasNext()) { Lot lot = (Lot) it.next(); System.out.println(lot.getNumber() + ": " + lot.getDescription()); // Include any details of a highest bid. Bid highestBid = lot.getHighestBid(); if(highestBid != null) { System.out.println(" Bid: " + highestBid.getValue()); } else { System.out.println(" (No bid)"); }

04/11/2004Lecture 4: Grouping Objects32 Type Casting Lot lot = (Lot) it.next(); the return value of the Iterator method next() is an object of type Object. To store this in an object of type Lot we need to explicitly convert it that type. This is called Casting This can only been done if the objects we have added to the container were originally of type Lot.

04/11/2004Lecture 4: Grouping Objects33 Type Casting Collections in Java allow for the storage of any type of objects. In order to do so it transforms everything you add into an object of type Object. When retrieving objects from a collection we normally cast them back into their original types.

04/11/2004Lecture 4: Grouping Objects34 Wrapper Classes Container classes in Java can only contain objects. Primitive types can therefore not be added. To solve this, Java provides wrapper classes: Integer, Float, Double Integer a = new Integer(10); int b = a.intValue();

04/11/2004Lecture 4: Grouping Objects35 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.

04/11/2004Lecture 4: Grouping Objects36 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.

04/11/2004Lecture 4: Grouping Objects37 The weblog-analyzer project

04/11/2004Lecture 4: Grouping Objects38 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

04/11/2004Lecture 4: Grouping Objects39 The hourCounts array

04/11/2004Lecture 4: Grouping Objects40 Using an array Square-bracket notation is used to access an array element: hourCounts[...] The number of elements of an array can be obtained via: hourCounts.length Elements are used like ordinary variables. On the left of an assignment: hourCounts[hour] =...; In an expression: adjusted = hourCounts[hour] – 3; hourCounts[hour]++; Arrays are passed by reference while their elements are passed by value.

04/11/2004Lecture 4: Grouping Objects41 The for loop Similar to a while loop. Often used to iterate a fixed number of times. Often used to iterate over an array.

04/11/2004Lecture 4: Grouping Objects42 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 }

04/11/2004Lecture 4: Grouping Objects43 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

04/11/2004Lecture 4: Grouping Objects44 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 often used to iterate over arrays.

04/11/2004Lecture 4: Grouping Objects45 Concepts Java API packages import ArrayList Iterator type cast for while array a++ ++a null