Grouping objects Introduction to collections 5.0.

Slides:



Advertisements
Similar presentations
Chapter 22 Implementing lists: linked implementations.
Advertisements

Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
Lists Chapter 4 Carrano, Data Structures and Abstractions with Java, Second Edition, (c) 2007 Pearson Education, Inc. All rights reserved X.
Lab 10: Bank Account II Transaction List, error checking & aggregation.
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.
Improving structure with inheritance
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.
Understanding class definitions Looking inside classes 3.0.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
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.
Modul 3 Collections af objekter Arraylist Collections Objektorienteret design og Java. 4.0.
Programming with Collections Grouping & Looping - Collections and Iteration Week 7.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Random, Collections & Loops Chapter 5 Copyright © 2012 Pearson Education, Inc.
Grouping objects Collections and iterators. Main concepts to be covered Collections Loops Iterators.
Designing classes How to write classes in a way that they are easily understandable, maintainable and reusable 3.0.
Improving structure with inheritance Main concepts to be covered Inheritance Subtyping Substitution Polymorphic variables Objects First with Java.
REPETITION CITS1001. Scope of this lecture Repetition for loops while loops 2.
Improving structure with inheritance Main concepts to be covered Inheritance Subtyping Substitution Polymorphic variables Objects First with Java.
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.
COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo-Cordero, MS.
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)
Understanding class definitions
Objects First With Java A Practical Introduction Using BlueJ Supplementary Material for Java
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.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
M1G Introduction to Programming 2 3. Creating Classes: Room and Item.
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.
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: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Collections and Iteration Week 13.  Collections  ArrayList objects  Using loops with collections Collections and Iteration CONCEPTS COVERED THIS WEEK.
Collections Dwight Deugo Nesa Matic
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,
LINKED LISTS.
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 Introduction to collections
COS 260 DAY 7 Tony Gauvin.
Functional Processing of Collections (Advanced)
Objects First with Java Introduction to collections
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
Understanding class definitions
Collections and iterators
COS 260 DAY 4 Tony Gauvin.
Improving structure with inheritance
Collections and iterators
Presentation transcript:

Grouping objects Introduction to collections 5.0

2 Main concepts to be covered Collections to group objects ( e.g. ArrayList ) Builds on the abstraction theme to simplify a problem into components Start making use of existing Java library classes to save time coding Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

3 Requirement to group objects Many applications with collections of objects: –Personal calendars store events –Library catalogs store book information –Student-record systems store student info –Music organizer store song filenames The dynamic number of items may have the following operations for its varying items: –Retrieved –Added –Deleted Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

4 An organizer for music files COLLECTION Contains a group of songs ITEMS Songs are stored as its filename only No pre-defined limit on the number of songs OPERATIONS Song files may be added Song files may be deleted How many song files are stored ( i.e. size ) Get a song filename from the group Explore the music-organizer-v1 project Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

5 Music collection example MusicOrganizer CLASS * MusicOrganizer containing various song files FIELDS * Dynamic ArrayList storage for a varying number of song String filenames METHODS * addFile * removeFile * getNumberOfFiles * listFile Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

6 Class libraries Provides many useful classes (e.g. String) Don’t have to write class from scratch Java calls its libraries packages Use library classes the same way as classes that you write (i.e constructor/methods) But do not appear in BlueJ class diagram Grouping objects is a recurring requirement that is handled in the java.util package (e.g. ArrayList) ArrayList library class will: –group the unsorted but ordered items –store item details –handle general access to the items

7 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling import java.util.ArrayList; // import statement // first line of file /** // before class definition *... */ public class MusicOrganizer { // Storage for an arbitrary number of file names. private ArrayList files; /** * Perform any initialization required for the * organizer. */ public MusicOrganizer() { files = new ArrayList (); }... }

8 Collections We specify... –collection type: ArrayList –containing objects of type: We say... “ArrayList of String” private ArrayList files; myMusic: MusicOrganizer  files null * Only 1 field named files is defined for the entire class

9 Generic classes for items of any type ArrayList These collections are known and defined as parameterized or generic types parameter type between the angle brackets is the object type of the items in the list — ArrayList An ArrayList may store any object type, but ALL objects in the list will be the same type Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

10 Creating an ArrayList object in the constructor In Java versions prior to version 7 files = new ArrayList ( ); Java 7 introduced ‘diamond notation’ files = new ArrayList ( ); where the type parameter can be inferred from the variable it is being assigned to myMusic: MusicOrganizer  files :ArrayList new

11 Key methods of class ArrayList The ArrayList class implements list functionality with methods for the following operations: — add(item) — remove(item) — get(index) — size()

12 Object structures with ArrayList collections Only a single field that stores an object of type ArrayList All work to access and manage the data is done in ArrayList object Benefits of abstraction by not knowing details of how work is done Helps us avoid duplication of information and behavior

13 Adding a third file Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Dynamic capacity with ability to increase and/or decrease as needed with its add( ) and remove( ) methods Keeps an internal count of the number of items with size( ) method returning that count Maintains the items in the order inserted with each new item added to the end of the list As an item is removed, all items following after the removed item are shifted up and forward in order to fill the removed item’s space

14 Features of the collection It increases its capacity as necessary It keeps a private count of the number of items in the list –size() accessor It keeps the objects in order of adding, but is otherwise unsorted Details of how this is done are hidden –Does that matter? –Does not knowing prevent us from using it? Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

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

16 ArrayList Index numbering Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Implicit numbering which starts with index 0 (same as String class) Last item in the collection has the index size-1 Thus, valid index values would be between [0... size( )-1]

17 Retrieving an object Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Index validity checks between [0 … size-1] 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. } Retrieve and print the file name Needed? (Error message?)

18 Removal may affect numbering Removal process may change index values of other objects in the list Collection moves all subsequent items up by 1 position to fill the gap Indices of items in front of (preceding) the removed item are UNCHANGED Indices of items after (following) the removed item are decreased by 1 Same “ shifting ” of items may also occur if adding new items into positions other than the end files.remove(1);

19 The general utility of indices Index values: –start at 0 –are numbered sequentially –have no gaps in consecutive objects Using integers to index collections has a general utility: –next: index + 1 –previous: index – 1 –last: list.size( ) – 1 –the first three: items at indices 0, 1, 2 We could use loops and iteration to access items in sequence: 0, 1, 2, …

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

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

22 Interlude: Some popular errors... Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

23 /** * Print out info (number of entries). */ public void showStatus() { if(files.size() == 0); { System.out.println("Organizer is empty"); } else { System.out.print("Organizer holds "); System.out.println(files.size() + " files"); } } Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling What’s wrong here?

24 /** * Print out info (number of entries). */ public void showStatus() { if(files.size() == 0); { System.out.println("Organizer is empty"); } else { System.out.print("Organizer holds "); System.out.println(files.size() + "files"); } } Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling This is the same as before!

25 /** * Print out info (number of entries). */ public void showStatus() { if(files.size() == 0) ; { System.out.println("Organizer is empty"); } else { System.out.print("Organizer holds "); System.out.println(files.size() + "files"); } } Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling This is the same again

26 /** * Print out info (number of entries). */ public void showStatus() { if(files.size() == 0) { ; } { System.out.println("Organizer is empty"); } else { System.out.print("Organizer holds "); System.out.println(files.size() + "files"); } } Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling and the same again…

27 /** * Print out info (number of entries). */ public void showStatus() { if(isEmpty = true) { System.out.println("Organizer is empty"); } else { System.out.print("Organizer holds "); System.out.println(files.size() + "files"); } } Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling This time I have a boolean field called ‘isEmpty’... What’s wrong here?

28 /** * Print out info (number of entries). */ public void showStatus() { if(isEmpty == true) { System.out.println("Organizer is empty"); } else { System.out.print("Organizer holds "); System.out.println(files.size() + "files"); } } Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling This time I have a boolean field called ‘isEmpty’... The correct version

29 /** * Store a new file in the organizer. If the * organizer is full, save it and start a new one. */ public void addFile(String filename) { if(files.size() == 100) files.save(); // starting new list files = new ArrayList (); files.add(filename); } Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling What’s wrong here?

30 /** * Store a new file in the organizer. If the * organizer is full, save it and start a new one. */ public void addFile(String filename) { if(files.size == 100) files.save(); // starting new list files = new ArrayList (); files.add(filename); } Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling This is the same.

31 /** * Store a new file in the organizer. If the * organizer is full, save it and start a new one. */ public void addFile(String filename) { if(files.size == 100) { files.save(); // starting new list files = new ArrayList (); } files.add(filename); } Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling The correct version

Grouping objects Collections and the for-each loop

33 Main concepts to be covered Collections Loops: the for-each loop Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

34 Iteration We often want to perform some actions an arbitrary number of times –e.g. print ALL the file names in the organizer –How many are there? Most programming languages include loop statements or iterative control structures to make this possible Java has several sorts of loop statement –We will start with its for-each loop Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

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

36 For-each loop pseudo code Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling for(ElementType element : collection) { loop body } For each element in collection, do the things in the loop body. ** where element is indeed a variable declaration of type ElementType and the variable is known as the loop variable 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

37 A Java example Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling /** * 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 for keyword introduces loop with details between ( ) loop variable filename is declared of type String loop body repeated for each element in files ArrayList each time, variable filename holds one of the elements allows access to the object for that particular element

38 Review Loop statements allow a block of statements to be repeated. The for-each loop allows iteration over a whole collection. But the for-each loop does NOT provide the index position of the current element. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

39 Selective processing Statements can be nested, giving greater selectivity: public void findFiles(String searchString) { for(String filename : files) { if(filename.contains(searchString)) { System.out.println(filename); } } ** using if statement to only print filenames matching the searchString

40 Critique of for-each Only use for any type of collection Accesses each element in sequence Same action for each element but may use selective filter using if statements Easy to write Termination happens naturally But, the collection cannot be changed There is no index provided during access –Not all collections are index-based Can NOT stop part way through loop –e.g. Find-the-first-that-matches Provides definite iteration of ENTIRE list –a.k.a. bounded iteration

41 for-each PROS easy to use access to ALL items one-by-one ability to change the state of the item terminates automatically selective filter using if-else statements actions in body may be complicated with multiple lines use on ANY type of collection abstraction from details of how handling occurs CONS no index provided can NOT stop during looping definite iteration of ALL items can NOT remove or add elements during loop use for collections only access must be to ALL items in sequence [0 to size-1]