Presentation is loading. Please wait.

Presentation is loading. Please wait.

Objects First with Java CITS1001 week 4

Similar presentations


Presentation on theme: "Objects First with Java CITS1001 week 4"— Presentation transcript:

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

2 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

3 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

4 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

5 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

6 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

7 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

8 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

9 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.

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

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

12 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

13 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

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

15 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

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

17 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, …

18 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.

19 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

20 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

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

22 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

23 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

24 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

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

26 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); } }

27 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?

28 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.

29 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.

30 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’

31 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

32 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

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

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

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

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

37 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

38 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

39 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

40 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

41 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

42 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

43 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

44 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

45 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

46 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.

47 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


Download ppt "Objects First with Java CITS1001 week 4"

Similar presentations


Ads by Google