Вы находитесь на странице: 1из 54

Session 3 - Exception-Handling

Java Programming
1
1 TCS Confidential
Collection Framework
(java.util Package)
Session 3 - Exception-Handling
Java Programming
2
2 TCS Confidential
Framework (in software):
a general system of
components for
architectural solutions.
Collection:
any collection of Objects
Session 3 - Exception-Handling
Java Programming
3
3 TCS Confidential
Overview (contd)
Collection, Iterator
Lists, ListIterator
List
ArrayList
LinkedList
Stack
Queue,
PriorityQueue
Sets
Set
TreeSet
HashSet
Maps
Map
TreeMap
HashMap
All the interfaces and classes are part of the java.util package.
Session 3 - Exception-Handling
Java Programming
4
4 TCS Confidential
Overview
(contd)
interface
Collection
interface
Iterator
interface
Comparable
interface
Comparator
interface
Queue
interface
Map
Stack
PriorityQueue
HashMap TreeMap
LinkedList ArrayList TreeSet HashSet
interface
List
interface
Set
interface
ListIterator
Collection
Set
TreeSet
HashSet
List
ArrayList
LinkedList
TreeSet
TreeMap
PriorityQueue
Session 3 - Exception-Handling
Java Programming
5
5 TCS Confidential
Holds references to objects
Can contain references to two
equal objects.(a.equals (b))
An object can change while in a
collection
(unless it is immutable).
Session 3 - Exception-Handling
Java Programming
6
6 TCS Confidential
Overview (contd)
Collection<E>
List<E>
Stack<E>
Set<E>
A map takes two object type
parameters:
Map<K,V>
Because collections work
with different types, these
are called generic
collections or generics
Session 3 - Exception-Handling
Java Programming
7
7 TCS Confidential
Collection, Iterator
Collection interface
represents any collection.
A collection has its own
iterator(s).
(returned iterator method);
The traversal sequence
depends on the collection.
interface
Collection
interface
Iterator
Session 3 - Exception-Handling
Java Programming
8
8 TCS Confidential
Collection<E> Methods
boolean isEmpty ()
int size ()
boolean contains (Object obj)
boolean add (E obj)
boolean remove (E obj)
Iterator<E> iterator ()
Supplies an
iterator for this
collection
interface
Collection
interface
Iterator
Session 3 - Exception-Handling
Java Programming
9
9 TCS Confidential
Iterator<E> Methods
boolean hasNext ()
E next ()
void remove ()
What is next is
determined
Removes the
last visited
element
interface
Collection
interface
Iterator
Session 3 - Exception-Handling
Java Programming
10
10 TCS Confidential
Iterator For Each Loop
Iterator<String> iter =
words.iterator();
while (iter.hasNext ())
{String word = iter.next ();
< ... process word > }
Collection<String> words =
new ArrayList<String>();
Session 3 - Exception-Handling
Java Programming
11
11 TCS Confidential
Lists, ListIterator
In a list all elements are numbered
a
0
, a
1
, ..., a
n-1
java.util:
List interface
ArrayList
LinkedList
ListIterator is an extended
iterator, (subinterface of Iterator)
Session 3 - Exception-Handling
Java Programming
12
12 TCS Confidential
Lists (contd)
interface
Collection
interface
Iterator
interface
ListIterator
ArrayList LinkedList
interface
Set
interface
List
Session 3 - Exception-Handling
Java Programming
13
13 TCS Confidential
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)
List<E> Methods
interface
Collection
interface
Iterator
interface
ListIterator
interface
List
Returns a ListIterator that starts iterations at index i
Session 3 - Exception-Handling
Java Programming
14
14 TCS Confidential
ListIterator<E> Methods
int nextIndex ()
boolean hasPrevious ()
E previous ()
int previousIndex ()
void add (E obj)
void set (E obj)
Can traverse the list backward
(inserts after the last visited
element)
Can change elements (changes the
last visited element)
Session 3 - Exception-Handling
Java Programming
15
15 TCS Confidential
ArrayList
Represents a list as a
dynamic array
Provides random access to the
elements
Implements all the methods of
List<E>
interface
List
ArrayList LinkedList
...
Session 3 - Exception-Handling
Java Programming
16
16 TCS Confidential
LinkedList
Doubly-linked list
with a header node.
Implements the
methods of List<E>
a
0
a
1
a
2
a
n-1
...
header
interface
List
ArrayList LinkedList
Session 3 - Exception-Handling
Java Programming
17
17 TCS Confidential
LinkedList (contd)
Additional methods
interface
List
ArrayList LinkedList
void addFirst (E obj)
void addLast (E obj)
E getFirst ()
E getLast ()
E removeFirst ()
E removeLast ()
Session 3 - Exception-Handling
Java Programming
18
18 TCS Confidential
ArrayList vs. LinkedList
Implements
array
+Provides
random access
- Insert, removing
elements shifts
elements
- Needs to be
resized
Implements list
-No random access
+Insert, removing
elements is done
by rearranging the
links
+Nodes are
dynamically added
Session 3 - Exception-Handling
Java Programming
19
19 TCS Confidential
ArrayList vs. LinkedList (contd)
for (int i = 0; i < list.size(); i++)
{
Object x = list.get (i);
...
}
Iterator iter = list.iterator ( );
while (iter.hasNext ( ))
{
Object x = iter.next ( );
...
}
for (Object x : list)
{
...
}
Session 3 - Exception-Handling
Java Programming
20
20 TCS Confidential
Stacks
Provides temporary storage LIFO
(Last-In-First-Out) manner.
Useful in nested structures
methods calling other methods
push and pop.
Implemented as java.util.Stack<E>
class
Session 3 - Exception-Handling
Java Programming
21
21 TCS Confidential
Stacks (contd)
Stack
Session 3 - Exception-Handling
Java Programming
22
22 TCS Confidential
Stack<E> Methods
boolean isEmpty ()
E push (E obj)
E pop ()
E peek ()
Returns obj; use
as void
Returns the top
element without
removing it from
the stack
Session 3 - Exception-Handling
Java Programming
23
23 TCS Confidential
Queues
Provides temporary storage in
the FIFO manner.
Useful in events that have to be
processed in order of their
arrival
java.util:
Queue interface
LinkedList (implements
Queue)
Session 3 - Exception-Handling
Java Programming
24
24 TCS Confidential
Queues (contd)
LinkedList
interface
Queue
Session 3 - Exception-Handling
Java Programming
25
25 TCS Confidential
Queue<E>
Methods
LinkedList
interface
Queue
boolean isEmpty ()
boolean add (E obj)
E remove ()
E peek ()
Returns the first element
without removing it from the
queue
Session 3 - Exception-Handling
Java Programming
26
26 TCS Confidential
Queues (contd)
Queue<Message> q =
new LinkedList<Message> ();
Methods added to LinkedList to implement
Queue interface:
add == addLast
remove== removeFirst
peek == getFirst
Session 3 - Exception-Handling
Java Programming
27
27 TCS Confidential
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)
Session 3 - Exception-Handling
Java Programming
28
28 TCS Confidential
PriorityQueue
interface
Queue
Priority Queues (contd)
The same methods as in
Queue: isEmpty, add,
remove, peek.
Session 3 - Exception-Handling
Java Programming
29
29 TCS Confidential
Sets
A set is without duplicate values
Designed for finding a value
quickly
java.util:
Set interface
TreeSet
HashSet
Session 3 - Exception-Handling
Java Programming
30
30 TCS Confidential
Sets (contd)
interface
Collection
TreeSet HashSet
interface
Set
Session 3 - Exception-Handling
Java Programming
31
31 TCS Confidential
TreeSet<E>
Works with Comparable
objects
contains, add, and remove
methods
Iterator returns elements in
ascending order
TreeSet HashSet
interface
Set
Session 3 - Exception-Handling
Java Programming
32
32 TCS Confidential
HashSet<E>
Works with objects for which
reasonable hashCode and
equals methods are defined
contains, add, and remove
methods
Iterator returns elements in no
particular order
TreeSet HashSet
interface
Set
Session 3 - Exception-Handling
Java Programming
33
33 TCS Confidential
Maps
It represents a correspondence
between a set of keys , values
Only one value can correspond
to a given key;
several keys can be mapped
onto the same value
keys values
Session 3 - Exception-Handling
Java Programming
34
34 TCS Confidential
Maps (contd)
TreeMap HashMap
interface
Map
Session 3 - Exception-Handling
Java Programming
35
35 TCS Confidential
Map<K, V> Methods
TreeMap HashMap
interface
Map
boolean isEmpty ()
int size ()
V get (K key)
V put (K key, V value)
V remove (K key)
Set<K> keySet ()
Session 3 - Exception-Handling
Java Programming
36
36 TCS Confidential
TreeMap<K,V>
Works with Comparable keys
containsKey, get, and put
methods
TreeMap HashSet
interface
Map
Session 3 - Exception-Handling
Java Programming
37
37 TCS Confidential
HashMap<K,V>
Works with keys for which
reasonable hashCode and equals
methods are defined
containsKey, get, and put methods
TreeMap HashMap
interface
Map
Session 3 - Exception-Handling
Java Programming
38
38 TCS Confidential
Example:
traversing all key-value
pairs
import java.util.*;
Map<Integer, String> AuctionItems =
new TreeMap<Integer, String> ();
AuctionItems.put (1, ARTPEICE);
...
for (Integer key : AuctionItems.keySet() )
{ String name = AuctionItems.get (key);
System.out.println (key + " : " + name);}
Session 3 - Exception-Handling
Java Programming
39
39 TCS Confidential
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.
Session 3 - Exception-Handling
Java Programming
40
40 TCS Confidential
Review (contd):
What are the properties of a list?
Name the key methods of the List interface.
How is ArrayList implemented?
How is LinkedList implemented?
Session 3 - Exception-Handling
Java Programming
41
41 TCS Confidential
Case Study: Stock Exchange
Implements a Suryodaya stock
exchange
Uses TreeSet, TreeMap, HashMap, Queue,
and PriorityQueue classes
A chance to practice structural and
object-oriented design
Session 3 - Exception-Handling
Java Programming
42
42 TCS Confidential
Stock Market Basics
Stocks are listed on a stock exchange, such
as Suryodaya Stock Exchange.
A particular stock is identified by its trading
symbol (for example, SUNW for Sun
Microsystems or MSFT for Microsoft)
Stocks are usually traded in multiples of 100
Stock prices are in Rs.
Online brokerage firms allow customers to
trade stocks online from their computers
Session 3 - Exception-Handling
Java Programming
43
43 TCS Confidential
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)
Session 3 - Exception-Handling
Java Programming
44
44 TCS Confidential
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
Session 3 - Exception-Handling
Java Programming
45
45 TCS Confidential
SafeTrade Program (contd)
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 users account.
Session 3 - Exception-Handling
Java Programming
46
46 TCS Confidential
SafeTrade Program (contd)
Session 3 - Exception-Handling
Java Programming
47
47 TCS Confidential
Session 3 - Exception-Handling
Java Programming
48
48 TCS Confidential
Session 3 - Exception-Handling
Java Programming
49
49 TCS Confidential
SafeTrade Program Design
Structural
Design
OO
Design
Detailed
Design
Classes and
objects
Data structures
used
Fields, constructors,
and methods
Session 3 - Exception-Handling
Java Programming
50
50 TCS Confidential
SafeTrade Structural Design
Queue =>
PriorityQueue<TradeOrder>
(with descending price
comparator)
Buy orders for each
stock
Queue =>
PriorityQueue<TradeOrder>
(with ascending price
comparator)
Sell orders for each
stock
Map => HashMap<String, Stock> Listed stocks
Queue => LinkedList<String> Mailbox for each
trader
Set => TreeSet<Trader> Logged-in traders
Map => TreeMap<String, Trader> Registered traders
interface => class Data
Session 3 - Exception-Handling
Java Programming
51
51 TCS Confidential
Structural Design
Tradeoffs
Registered users:
large number (100,000s)
access time is not critical
Binary
Search
Tree
(TreeMap)
Listed stocks:
relatively small number
fast access time is critical
Session 3 - Exception-Handling
Java Programming
52
52 TCS Confidential
SafeTrade OO Design

SafeTrade
StockExchange Brokerage
TraderWindow
Trader Stock
PriceComparator
TradeOrder
LoginWindow
interface
Login
StockExchange
Brokerage
Stock
Trader
TraderWindow
PriceComparator
Session 3 - Exception-Handling
Java Programming
53
53 TCS Confidential
Part 1: Trader registration and login
SafeTrade LoginWindow
interface
Login
Session 3 - Exception-Handling
Java Programming
54
54 TCS Confidential
Part 2: Stocks and orders
TraderWindow