Objects First with Java CITS1001 week 4

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

Chapter 10 Introduction to Arrays
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.
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
Grouping Objects 3 Iterators, collections and the while loop.
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
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.
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.
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.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
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.
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.
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.
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,
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Coming up ArrayList ArrayList vs Array – Declaration – Insertion – Access – Removal Wrapper classes Iterator object.
Chapter 8: Understanding Collections Textbook: Chapter 4.
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
EECE 310: Software Engineering
Objects First with Java Introduction to collections
Chapter 20 Generic Classes and Methods
Chapter 5: Control Structures II
Loop Structures.
COS 260 DAY 7 Tony Gauvin.
Functional Processing of Collections (Advanced)
COS 260 DAY 9 Tony Gauvin.
More sophisticated behavior
Objects First with Java Introduction to collections
Arrays, For loop While loop Do while loop
Understanding class definitions
Topics Introduction to File Input and Output
COS 260 DAY 10 Tony Gauvin.
COS 260 DAY 18 Tony Gauvin.
Java Programming Arrays
COS 260 DAY 8 Tony Gauvin.
COS 260 DAY 8 Tony Gauvin.
Programming II (CS300) Chapter 07: Linked Lists and Iterators
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)
Topics Introduction to File Input and Output
Collections and iterators
Arrays.
Presentation transcript:

Objects First with Java CITS1001 week 4 Grouping objects CITS1001 week 4 © David J. Barnes and Michael Kölling

Objects First with Java Fundamental concepts The ArrayList collection Process all items: the for-each loop Reading: Chapter 4 (section 4.1 to 4.9) of Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling © David J. Barnes and Michael Kölling

The requirement to group objects Objects First with Java The requirement to group objects Many applications involve collections of objects Personal organizers Library catalogs Student-record system etc. Entries must be accessed efficiently The number of items to be stored varies Need the ability to add and delete items © David J. Barnes and Michael Kölling

An organizer for music files Objects First with Java An organizer for music files Track files may be added and deleted There is no pre-defined limit to the number of files It will tell how many file names are stored in the collection It will list individual file names Explore the music-organizer-v1 project Grouping objects is a recurring requirement The java.util package contains classes for doing this © David J. Barnes and Michael Kölling

Objects First with Java import java.util.ArrayList; /** * ... */ public class MusicOrganizer { // Storage for an arbitrary number of file names. private ArrayList<String> files;   * Perform any initialization required for the * organizer. public MusicOrganizer() files = new ArrayList<String>(); } ... © David J. Barnes and Michael Kölling

Objects First with Java Collections We specify The type of the collection: ArrayList The type of the objects it will contain: <String> private ArrayList<String> files; We say “ArrayList of String” © David J. Barnes and Michael Kölling

Objects First with Java Generic classes Collections are known as parameterized or generic types ArrayList implements list functionality: add, remove, size, get, etc. The type parameter says what we want a list of: ArrayList<Person> ArrayList<TicketMachine> etc. © David J. Barnes and Michael Kölling

Creating an ArrayList object In versions of Java prior to version 7 files = new ArrayList<String>(); Java 7 introduced ‘diamond notation’ files = new ArrayList<>(); The type parameter can be inferred from the variable being assigned to A convenience

Exercises 4.4 Write a declaration of a private field named library that can hold an ArrayList. The elements of the ArrayList are of type Book. 4.5 Write a declaration of a local variable called cits1001 that can hold an ArrayList of Student. 4.6 Write a declaration of a private field called tracks for storing a collection of MusicTrack objects. 4.7 Write assignments to the library, cits1001, and track variables to create the appropriate ArrayList objects. Write them once using diamond notation and once without diamond notation, specifying the full type.

Object structures with collections Objects First with Java Object structures with collections © David J. Barnes and Michael Kölling

Objects First with Java Adding a third file © David J. Barnes and Michael Kölling

Features of the collection Objects First with Java Features of the collection It increases its capacity as necessary It keeps a private count: With the size() accessor It keeps the objects in order Details of how all this is done are hidden Does that matter? Does not knowing how it works prevent us from using it? © David J. Barnes and Michael Kölling

Objects First with Java Using the collection public class MusicOrganizer { private ArrayList<String> files; ...   public void addFile(String filename) files.add(filename); } public int getNumberOfFiles() return files.size(); Adding a new file Returning the number of files (delegation) © David J. Barnes and Michael Kölling

Objects First with Java Index numbering © David J. Barnes and Michael Kölling

Objects First with Java Retrieving an object public void listFile(int index) { if(index >= 0 && index < files.size()) { String filename = files.get(index); System.out.println(filename); } else { // This is not a valid index. Index validity checks Retrieve and print the file name Needed? (Error message?) © David J. Barnes and Michael Kölling

Removal may affect numbering Objects First with Java Removal may affect numbering © David J. Barnes and Michael Kölling

The general utility of indices Using integers to index collections has a general utility: ‘next’ is index + 1 ‘previous’ is index – 1 ‘last’ is list.size() – 1 ‘the first three’ is the items at indices 0, 1, 2 We could also think about accessing items in sequence: 0, 1, 2, …

Exercises 4.8 If a collection stores 10 objects, what value would be returned from a call to its size method? 4.9 Write a method call using get to return the 5th object stored in a collection called items. 4.10 What is the index of the last item stored in a collection of 15 objects? 4.11 Write a method call to add the object held in the variable favouriteTrack to a collection called files. 4.12 Write a method call to remove the 3rd object stored in a collection called dates.

Objects First with Java 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 © David J. Barnes and Michael Kölling

Objects First with Java 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 © David J. Barnes and Michael Kölling

Loops A loop can be used to execute a block of statements repeatedly without having to write them multiple times

Iteration fundamentals Objects First with Java Iteration fundamentals We often want to repeat some actions over and over e.g. “do this action for each student in the university” e.g. “do this action seventeen times” e.g. “do this action until this condition is true” Java loops provide us with a way to control how many times we repeat these actions With collections, we often want to repeat things once for every object in a particular collection © David J. Barnes and Michael Kölling

For-each loop pseudo code Objects First with Java 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. © David J. Barnes and Michael Kölling

Objects First with Java 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 © David J. Barnes and Michael Kölling

Questions Write lines of code for the following tasks Declare an ArrayList called cits1001 of Student objects. Initialise cits1001 (that is, create an ArrayList object). Implement a method, listAllStudentNames, that prints the names of each student. Assume method signatures as needed for your Student class.

Selective processing public void findFiles(String searchString) { Statements can be nested, giving greater selectivity: public void findFiles(String searchString) { for(String filename : files) { if(filename.contains(searchString)) { System.out.println(filename); } }

Questions (continued) Implement a method, classAverage, that returns the average mark for your cits1001 object. Challenge: which special conditions do you think this method should take into consideration? How would you handle those conditions?

Search and return pattern public String findFiles(String searchString) { for (String filename : files) { if (filename.contains(searchString)) { return filename; // return the first match if one is found } System.out.println(“No matching file name found”); return null; //return null object if NO match is found Error printing at the end is optional (see ex 4.26). BUT you must return some value – so for selective processing, always need to add a default case at the end. The compiler will insist on this. Later in the unit we will see some more systematic ways of error handling.

Questions (continued) Write the signature for a method, findStudent, that will search for a particular name in the cits1001 ArrayList and return the Student object associated with that name. Now write an implementation of your method Challenge: can you find a way to print a message, once the foreach loop has finished, if no student names matches the search string? Hint 1: use a boolean variable. Or Hint 2: use the search and return pattern.

Critique of for-each Easy to write Termination happens naturally The collection cannot be changed There is no index provided Not all collections are index-based We can’t stop part way through Except when using a return statement It provides ‘definite iteration’, aka ‘bounded iteration’

Process all items pattern The for-each loop is used whenever we need to perform some action on every item in a collection: view every one change every one check every one select some or count some from every one Examples: see MusicOrganiser.java and Club.java code in the handouts and MarksAnalyser in the labs

Summary of for-each rule 1. Get first element of the collection files 2. Execute statement using that value 3. Get next element from the collection and repeat from 2 4. But if no elements left then stop for (String filename : files) { if (filename.contains(searchString)) { System.out.println(filename); } } Remember we are learning the rule that the JVM uses to execute a for-each statement

Review (1) Collection Loop null (reminder) A collection object can store an arbitrary number of other objects Loop A loop can be used to execute a block of statements repeatedly without having to write them multiple times null (reminder) The Java reserved word null is used to mean “no object”. A field that has not explicitly been initialised will contain the value null by default.

Review (2) ArrayList<T> Foreach The simplest Java library for grouping objects: as an unsorted but ordered flexible-sized list. The type parameter T specifies the type of objects that will be stored in the list. Foreach The foreach loop can perform a set of actions repeatedly on a collection without having to write out the actions multiple times.

Objects First with Java Iterators Grouping objects Iterators also explain: how to pass an ArrayList for testing © David J. Barnes and Michael Kölling

Iterator and iterator() Collections have an iterator() method. This returns an Iterator object. Iterator<E> has three methods: boolean hasNext() E next() void remove()

Using an Iterator object Objects First with Java Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Using an Iterator object returns an Iterator object java.util.Iterator Iterator<ElementType> it = myCollection.iterator(); while(it.hasNext()) { call it.next() to get the next object do something with that object } public void listAllFiles() { Iterator<Track> it = files.iterator(); while(it.hasNext()) { Track tk = it.next(); System.out.println(tk.getDetails()); } © David J. Barnes and Michael Kölling

Objects First with Java Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Iterator mechanics © David J. Barnes and Michael Kölling

Objects First with Java Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling myList:List myList.iterator() :Element :Element :Element :Element :Iterator © David J. Barnes and Michael Kölling

Objects First with Java Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling myList:List :Element :Element :Element :Element :Iterator :Iterator ✔ hasNext()? next() Element e = iterator.next(); © David J. Barnes and Michael Kölling

Objects First with Java Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling myList:List :Element :Element :Element :Element :Iterator :Iterator ✔ hasNext()? next() © David J. Barnes and Michael Kölling

Objects First with Java Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling myList:List :Element :Element :Element :Element :Iterator :Iterator ✔ hasNext()? next() © David J. Barnes and Michael Kölling

Objects First with Java Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling myList:List :Element :Element :Element :Element :Iterator :Iterator hasNext()? ✔ next() © David J. Barnes and Michael Kölling

Objects First with Java Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling myList:List :Element :Element :Element :Element :Iterator ✗ hasNext()? © David J. Barnes and Michael Kölling

Objects First with Java 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. 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. © David J. Barnes and Michael Kölling

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.

Objects First with Java 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. © David J. Barnes and Michael Kölling