Java Methods
Object-Oriented Programming
and Data Structures
3rd AP edition
Maria Litvin ● Gary Litvin
map.put(20,
"Chapter");
The Java Collections Framework
Copyright © 2015 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.
Objectives:
• Learn a subset of the Java collections
framework
• Practice working on a realistic software
project as a team
20-2
Overview
• Framework (in software): a general system of
components and architectural solutions that
provides development tools to programmers
for use with a relatively wide range of
applications.
• Collection: (hmm...) any collection of
elements
20-3
Overview (cont’d)
• Collection, Iterator
• Lists, ListIterator



List
ArrayList
LinkedList
• Stack
• Queue, PriorityQueue
• Sets



Set
TreeSet
HashSet
• Maps



Map
TreeMap
HashMap
All these interfaces and classes are
part of the java.util package.
Names of interfaces are in italics.
20-4
Overview
(cont’d)
ArrayList
«interface»
Collection
«interface»
«interface»
List
Set
LinkedList
TreeSet
HashSet
«interface»
Queue
«interface»
Map
Stack
PriorityQueue
TreeMap
Collection
Set
TreeSet
HashSet
List
ArrayList
LinkedList
HashMap
«interface»
Iterator
«interface»
Comparable
«interface»
ListIterator
TreeSet
TreeMap
PriorityQueue
«interface»
Comparator
20-5
Overview (cont’d)
• A collection holds references to objects (but
we say informally that it “holds objects”).
• A collection can contain references to two
equal objects (a.equals(b)) as well as two
references to the same object (a == b).
• An object can belong to several collections.
• An object can change while in a collection
(unless it is immutable).
20-6
Overview (cont’d)
• Starting with Java 5, a collection holds
objects of a specified type. A collection
class’s or interface’s definition takes
object type as a parameter:




Collection<E>
List<E>
Stack<E>
Set<E>
Because collections
work with different
types, these are called
generic collections or
generics
• A map takes two object type parameters:

Map<K,V>
20-7
Collection, Iterator
«interface»
Iterator
«interface»
Collection
• Collection interface represents any collection.
• An iterator is an object that helps to traverse
the collection (process all its elements in
sequence).
• A collection supplies its own iterator(s),
(returned by collection’s iterator method); the
traversal sequence depends on the collection.
20-8
Collection<E>
Methods
boolean isEmpty ( )
int size ( )
boolean contains (Object obj)
boolean add (E obj)
boolean remove (E obj)
Iterator<E> iterator ( )
// ... other methods
«interface»
Iterator
«interface»
Collection
Supplies an
iterator for this
collection
20-9
Iterator<E>
Methods
«interface»
Iterator
boolean hasNext ( )
E next ( )
void remove ( )
«interface»
Collection
What’s “next” is
determined by a
particular collection
Removes the last
visited element
20-10
Iterator  “For Each” Loop
Collection<String> words = new ArrayList<String>();
...
for (String word : words)
{
< ... process word >
}
Iterator<String> iter =
words.iterator( );
while (iter.hasNext ( ))
{
String word = iter.next ( );
< ... process word >
}
A “for each” loop is a
syntactic shortcut that
replaces an iterator
20-11
Lists, ListIterator
• A list represents a collection in which all
elements are numbered by indices:
a0, a1, ..., an-1
• java.util:



List interface
ArrayList
LinkedList
• ListIterator is an extended iterator, specific
for lists (ListIterator is a subinterface of
Iterator)
20-12
Lists (cont’d)
«interface»
Collection
«interface»
Iterator
«interface»
ListIterator
«interface»
List
ArrayList
LinkedList
«interface»
Set
etc.
20-13
List<E>
Methods
«interface»
Iterator
«interface»
Collection
«interface»
ListIterator
«interface»
List
// All Collection<E> methods, plus:
E get (int i)
E set (int i, E obj)
void add (int i, E obj)
E remove (int i)
int indexOf (Object obj)
ListIterator<E> listIterator ( )
ListIterator<E> listIterator (int i)
These methods
are familiar from
ArrayList, which
implements List
Returns a ListIterator
that starts iterations at
index i
20-14
ListIterator<E>
Methods
«interface»
Iterator
«interface»
Collection
«interface»
ListIterator
«interface»
List
// The three Iterator<E> methods, plus:
int nextIndex ( )
boolean hasPrevious ( )
Can traverse the
E previous ( )
list backward
int previousIndex ( )
void add (E obj)
Can add elements to the list (inserts
void set (E obj)
after the last visited element)
Can change elements (changes
the last visited element)
20-15
ListIterator “Cursor” Positioning
[0]
value
[1]
value
[i-1]
...
value
previous()
listIterator(0)
[i]
value
[size()-1]
...
value
O
next()
listIterator(i)
listIterator(size())
iter.add(obj);
(Reverse links not shown)
20-16
«interface»
Iterator
ArrayList
«interface»
ListIterator
«interface»
List
ArrayList
LinkedList
• Represents a list as a dynamic array (array
that is resized when full)
• Provides random access to the elements
a0
a1
a2
... an-1
• Implements all the methods of List<E>
20-17
«interface»
List
«interface»
Iterator
LinkedList
«interface»
ListIterator
ArrayList
LinkedList
• Represents a list as a doubly-linked list
with a header node (Chapter 21)
header
a0
a1
a2
...
an-1
• Implements all the methods of List<E>
20-18
LinkedList
(cont’d)
«interface»
Iterator
«interface»
ListIterator
«interface»
List
ArrayList
LinkedList
• Additional methods specific to LinkedList:
void addFirst (E obj)
void addLast (E obj)
E getFirst ( )
E getLast ( )
E removeFirst ( )
E removeLast ( )
20-19
ArrayList
vs. LinkedList
• Implements a list as an array
• Implements a list as a
doubly-linked list with a
header node
+ Provides random access to
the elements
- No random access to the
elements — needs to
traverse the list to get to the
i-th element
- Inserting and removing
elements requires shifting of
subsequent elements
+ Inserting and removing
elements is done by
rearranging the links — no
shifting
- Needs to be resized when
runs out of space
+ Nodes are allocated and
released as necessary
20-20
ArrayList vs. LinkedList (cont’d)
ArrayList
LinkedList
get(i) and set(i, obj)
O(1)
O(n)
add(i, obj) and remove(i)
O(n)
O(n)
add(0, obj)
O(n)
O(1)
add(obj)
O(1)
O(1)
contains(obj)
O(n)
O(n)
20-21
ArrayList vs. LinkedList (cont’d)
for (int i = 0; i < list.size(); i++)
{
Object x = list.get (i);
...
}
Works well for an
ArrayList  O(n)
inefficient for a
LinkedList  O(n2)
Iterator iter = list.iterator ( );
while (iter.hasNext ( ))
{
Object x = iter.next ( );
...
}
for (Object x : list)
{
...
}
Work well for both
an ArrayList and a
LinkedList  O(n)
20-22
Stacks
• A stack provides temporary storage in the
LIFO (Last-In-First-Out) manner.
• Stacks are useful for dealing with nested
structures and branching processes:



pictures within pictures
folders within folders
methods calling other methods
• Controlled by two operations: push and pop.
• Implemented as java.util.Stack<E> class
20-23
Stacks (cont’d)
Stack
20-24
Stack<E>
Methods
boolean isEmpty ( )
E push (E obj)
E pop ( )
E peek ( )
Stack
Returns obj; use as void
Returns the top element
without removing it from
the stack
20-25
Queues
• A queue provides temporary storage in the
FIFO (First-In-First-Out) manner
• Useful for dealing with events that have to be
processed in order of their arrival
• java.util:


Queue interface
LinkedList (implements Queue)
20-26
Queues (cont’d)
«interface»
Queue
LinkedList
20-27
Queue<E>
Methods
«interface»
Queue
LinkedList
boolean isEmpty ( )
boolean add (E obj)
E remove ( )
E peek ( )
Returns the first element
without removing it from
the queue
20-28
Queues (cont’d)
Queue<Message> q =
new LinkedList<Message> ( );
Methods have been added to
LinkedList to implement the Queue
interface:
add
== addLast
remove == removeFirst
peek
== getFirst
All of the above work in O(1) time
20-29
Priority Queues
• In a priority queue, items are processed NOT
in order of arrival, but in order of priority.
• java.util:


Queue interface
PriorityQueue (implements Queue)
20-30
Priority Queues (cont’d)
«interface»
Queue
PriorityQueue
• The same methods as in Queue: isEmpty,
add, remove, peek.
20-31
PriorityQueue<E>
Class
«interface»
Queue
PriorityQueue
• Works with Comparable objects (or takes a
comparator as a parameter).
• The smallest item has the highest priority.
• Implements a priority queue as a min-heap
(Chapter 26).
• Both add and remove methods run in
O(log n) time; peek runs in O(1) time.
20-32
Sets
• A set is a collection without duplicate values
• What is a “duplicate” depends on the
implementation
• Designed for finding a value quickly
• java.util:



Set interface
TreeSet
HashSet
20-33
Sets (cont’d)
«interface»
Iterator
«interface»
Collection
«interface»
Set
Methods of Set<E> are the same
as methods of Collection<E>
TreeSet
HashSet
Set’s semantics are different
from Collection (no duplicates),
but Set does not add any new
methods.
20-34
TreeSet<E>
«interface»
Set
TreeSet
HashSet
• Works with Comparable objects (or takes a
comparator as a parameter)
• Implements a set as a Binary Search Tree
(Chapter 24)
• contains, add, and remove methods run in
O(log n) time
• Iterator returns elements in ascending order
20-35
«interface»
Set
HashSet<E>
TreeSet
HashSet
• Works with objects for which reasonable
hashCode and equals methods are defined
• Implements a set as a hash table
(Chapter 25)
• contains, add, and remove methods run in
O(1) time
• Iterator returns elements in no particular
order
20-36
Maps
• A map is not a collection; it represents a
correspondence between a set of keys and
a set of values
• Only one value can correspond to a given
key; several keys can be mapped onto the
same value
keys
values
20-37
Maps (cont’d)
• java.util:



Map interface
TreeMap
HashMap
«interface»
Map
TreeMap
HashMap
20-38
Map<K, V>
Methods
«interface»
Map
TreeMap
HashMap
boolean isEmpty ( )
int size ( )
V get (K key)
V put (K key, V value)
V remove (K key)
boolean containsKey (Object key)
Set<K> keySet ( )
Returns the set
of all keys
20-39
TreeMap<K,V>
«interface»
Map
TreeMap
HashSet
• Works with Comparable keys (or takes a
comparator as a parameter)
• Implements the key set as a Binary Search
Tree (Chapter 24)
• containsKey, get, and put methods run in
O(log n) time
20-40
HashMap<K,V>
«interface»
Map
TreeMap
HashMap
• Works with keys for which reasonable
hashCode and equals methods are defined
• Implements the key set as a hash table
(Chapter 25)
• containsKey, get, and put methods run in
O(1) time
20-41
Example:
traversing all key-value pairs in a map
import java.util.*;
...
Map<Integer, String> presidents =
new TreeMap<Integer, String> ( );
presidents.put (1, “George Washington”);
...
for (Integer key : presidents.keySet( ) )
{
String name = presidents.get (key);
System.out.println (key + " : " + name);
}
20-42
Review:
•
•
•
•
Why Java collections are called “generic”?
Name several methods of Collection.
What is an iterator?
How can we obtain an iterator for a given
collection?
• Guess what happens when we call iter.next( )
when there is no next element.
20-43
Review (cont’d):
•
•
•
•
•
What are the properties of a list?
Name the key methods of the List interface.
How is ArrayList implemented?
How is LinkedList implemented?
What is the big-O for the average run time for
get(i) in an ArrayList and a LinkedList?
20-44
Review (cont’d):
• Name a few methods specific to LinkedList.
• Name a few methods specific to ListIterator.
• Can you start iterations at any given position
in a list?
• How is a set different from a list?
• Name a few methods of the Set
interface.
20-45
Review (cont’d):
• What is the order of values returned by a
TreeSet iterator?
• What is a map?
• In a map, can the same key be associated
with several different values?
20-46
Case Study: Stock Exchange
• Implements a toy stock exchange
• Can be structured as a team development
project
• Uses TreeSet, TreeMap, HashMap, Queue,
and PriorityQueue classes
• A chance to practice structural and
object-oriented design
20-47
Stock Market Basics
• Stocks are listed on a stock exchange, such
as NYSE (New York Stock Exchange)
• A particular stock is identified by its trading
symbol (for example, GOOG for Google or
MSFT for Microsoft)
• Stocks are usually traded in multiples of 100
• Stock prices are in dollars and cents (can
include fractions of cents in the real world)
• Online brokerage firms allow customers to
trade stocks online from their computers
20-48
Stock Market Terms
• Buy order — an order to buy shares of stock
• Sell order — an order to sell shares of stock
• Limit order — specifies the maximum price for
a buy or a minimum price for a sell
• Ask — asking price for a sell order
• Bid — offer to buy at a certain price
• Market order — an order to buy or sell at the
market price (the lowest “ask” or the highest
“bid,” respectively)
20-49
SafeTrade Program
•
•
•
•
Registered users “trade” shares.
A user must login first.
The program can register a new user.
A logged in user can place buy and sell orders
and get price quotes for stocks.
• Users receive messages when their orders are
executed
20-50
SafeTrade Program (cont’d)
• Runs on a single computer; each active user
opens a separate trading window.
• Does not keep track of cash or of the number
of shares available on each user’s account.
20-51
SafeTrade Program (cont’d)
20-52
SafeTrade Program Design
Data structures
used
Structural
Design
Classes and
objects
OO
Design
Detailed
Design
Fields, constructors,
and methods
20-53
SafeTrade Structural Design
Data
interface => class
Registered traders
Map => TreeMap<String, Trader>
Logged-in traders
Set => TreeSet<Trader>
Mailbox for each trader
Queue => LinkedList<String>
Listed stocks
Map => HashMap<String, Stock>
Sell orders for each
stock
Queue => PriorityQueue<TradeOrder>
(with ascending price comparator)
Buy orders for each
stock
Queue => PriorityQueue<TradeOrder>
(with descending price comparator)
20-54
Structural Design —
Tradeoffs
Registered users:
• large number (100,000s)
• access time is not critical
Listed stocks:
• relatively small number
• fast access time is critical
Binary Search Tree
(TreeMap)
Hash table
(HashMap)
OK to sacrifice some
wasted space for better
performance
20-55
SafeTrade OO Design
SafeTrade
LoginWindow
TraderWindow
«interface»
Login
StockExchange
Brokerage
Stock
Trader
PriceComparator
StockExchange
Brokerage
Stock
Trader
TraderWindow
PriceComparator
TradeOrder
20-56
SafeTrade OO Design (cont’d)
• Part 1: Trader registration and login
SafeTrade
A small
main
class
LoginWindow
TraderWindow
«interface»
Login
StockExchange
Brokerage
Stock
Trader
PriceComparator
StockExchange
Brokerage
Stock
Trader
TraderWindow
PriceComparator
Keeps track of
registered and
logged in traders
TradeOrder
20-57
SafeTrade OO Design (cont’d)
• Part 2: Stocks and orders
SafeTrade
LoginWindow
TraderWindow
«interface»
Login
Keeps
track of
listed
stocks
Represents
one stock;
keeps track
of all orders
for the stock
StockExchange
Brokerage
Stock
Trader
PriceComparator
StockExchange
Brokerage
Stock
Trader
TraderWindow
PriceComparator
TradeOrder
Represents
one order
20-58
SafeTrade Detailed Design
• Describes constructors, fields, and methods.
• Documentation was generated automatically
from javadoc comments in the source code.
See
JM\Ch20\SafeTrade\SafeTradeDocs.zip
20-59
SafeTrade Program (cont’d)
SafeTrade
LoginWindow
TraderWindow
GUI (supplied
by us)
«interface»
Login
StockExchange
Stock
PriceComparator
Brokerage
Your job
(2-5 team
members)
Trader
StockExchange
Brokerage
Stock
Trader
TraderWindow
PriceComparator
TradeOrder
20-60
Review:
• Name a few collections classes used in
SafeTrade.
• What is a limit order?
• What is a market order?
• What data structures are used to hold sell
and buy orders for a given stock? Why?
• Why is HashMap a good choice to represent
listed stocks?
20-61
Review (cont’d):
• What data structure would be appropriate for
keeping track of stock holdings for each
trader?
• Explain the role of the Login interface in the
SafeTrade project.
20-62