Upload
candace-mathews
View
216
Download
1
Embed Size (px)
Citation preview
JAVA COLLECTIONS
M . TA I M O O R K H A NTA I M O O R K H A N @ C I I T- AT T O C K . E D U .P K
( A D A P T E D F R O M S W I N B U R N E N O T E S )
LEARNING OBJECTIVES
Students can explain why some objects need to hold collections of other objects
Students can write code to support this relationship
Students should be able to Search through collections Add and remove items form collections Create objects to manage collections of other objects
Students should be able to use iterators effectively
2
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.
3
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.
4
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.
5
JAVA.UTIL
“Contains the collections framework…date and time facilities,… string tokenizer.. random-number generator..”
ArrayList<E>, LinkedList<E>, Stack<E>
Calendar, Date
Formatter
Scanner
StringTokenizer
Random
Iterator<E>
6
7
import java.util.ArrayList;
/** * ... */public class Notebook{ // Storage for an arbitrary number of notes. private ArrayList<String> notes; /** * Perform any initialization required for the * notebook. */ public Notebook() { notes = new ArrayList<String>(); }
...}
COLLECTIONS
We specify: the type of collection: ArrayList the type of objects it will contain: <String>
We say, “ArrayList of String”.
8
OBJECT STRUCTURES WITH COLLECTIONS
9
ADDING A THIRD NOTE
10
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
USING THE COLLECTION
12
public class Notebook{ private ArrayList<String> 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)
INDEX NUMBERING
13
RETRIEVING AN OBJECT
14
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 < notes.size()) { System.out.println(notes.get(noteNumber)); } else { // This is not a valid note number. }}
REMOVAL MAY AFFECT NUMBERING
15
ArrayList implements list functionality: add, get, size, etc.
The type parameter says what we want a list of:
ArrayList<Person> ArrayList<TicketMachine> etc.
16
Interesting tutorial on genericshttp://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf
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
ITERATION
With collections, we often want to repeat things once for every object in a particular collection.
Most programming languages include loop statements to make this possible.
Java supports “do”, “while” and various “for” loops There is also a type called an “iterator”
18
FOR LOOP EXAMPLE
19
/** * 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
WHILE LOOP EXAMPLE
20
/** * List all notes in the notebook. */public void listNotes(){ int index = 0; while(index < notes.size()) { System.out.println(notes.get(index)); index++; }} 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
SEARCHING A COLLECTION
21
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.
ITERATORS
22
:Element
myList:List
:Element :Element
:Iterator
myList.iterator()
:Element
Ask myList for an iterator
23
:Element :Element :Element
:Iterator
hasNext()? ✔next()
Element e = iterator.next();
:Element
:Iterator
myList:List
24
:Element :Element :Element
hasNext()? ✔next()
:Element
:Iterator :Iterator
myList:List
25
:Element :Element :Element
hasNext()? ✔next()
:Element
:Iterator :Iterator
myList:List
26
:Element :Element :Element
hasNext()? ✔next()
:Element
:Iterator :Iterator
myList:List
27
:Element :Element :Element
hasNext()? ✗
:Element
:Iterator
myList:List
USING AN ITERATOR OBJECT
28
Iterator<ElementType> 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<String> it = notes.iterator(); while(it.hasNext()) { System.out.println(it.next()); }}
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.
29
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.
30
READING & EXERCISES
page 77 – page 86
page 88 – page 127
http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.htmlExercises will be specified in the lab handout.
Everything to the end of chapter 3 will be assessable in the first test
31