Title: Java Methods A
1The Java Collections Framework
.
2Objectives
- Learn a subset of the Java collections framework
3Overview
- 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
4Overview (contd)
- 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.
5Overview (contd)
6Overview (contd)
- 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).
7Overview (contd)
- Starting with Java 5, a collection holds objects
of a specified type. A collection classs or
interfaces definition takes object type as a
parameter - CollectionltEgt
- ListltEgt
- StackltEgt
- SetltEgt
- A map takes two object type parameters
- MapltK,Vgt
Because collections work with different types,
these are called generic collections or generics
8Collection, Iterator
interface Collection
interface Iterator
- 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 collections iterator method) the
traversal sequence depends on the collection.
9CollectionltEgt Methods
interface Collection
interface Iterator
boolean isEmpty () int size () boolean
contains (Object obj) boolean add (E obj)
boolean remove (E obj) IteratorltEgt iterator
() // ... other methods
Supplies an iterator for this collection
10IteratorltEgt Methods
interface Collection
interface Iterator
boolean hasNext () E next () void remove
()
Whats next is determined by a particular
collection
Removes the last visited element
11Iterator ? For Each Loop
CollectionltStringgt words new
ArrayListltStringgt() ...
IteratorltStringgt iter
words.iterator() while (iter.hasNext ())
String word iter.next () lt ...
process word gt
for (String word words) lt ... process
word gt
A for each loop is a syntactic shortcut that
replaces an iterator
12Lists, 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)
13Lists (contd)
interface Collection
interface Iterator
interface ListIterator
interface List
interface Set
etc.
14ListltEgt Methods
interface Collection
interface Iterator
interface ListIterator
interface List
// All CollectionltEgt 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) ListIteratorltEgt listIterator ()
ListIteratorltEgt listIterator (int i)
These methods are familiar from ArrayList, which
implements List
Returns a ListIterator that starts iterations at
index i
15ListIteratorltEgt Methods
interface Collection
interface Iterator
interface ListIterator
interface List
// The three IteratorltEgt methods, plus int
nextIndex () boolean hasPrevious () E
previous () int previousIndex () void add
(E obj) void set (E obj)
Can traverse the list backward
Can add elements to the list (inserts after the
last visited element)
Can change elements (changes the last visited
element)
16ListIterator Cursor Positioning
iter.add(obj)
(Reverse links not shown)
17ArrayList
interface List
interface Iterator
interface ListIterator
- Represents a list as a dynamic array (array that
is resized when full) - Provides random access to the elements
- Implements all the methods of ListltEgt
a1
a2
an-1
...
a0
18LinkedList
interface List
interface Iterator
interface ListIterator
- Represents a list as a doubly-linked list with a
header node - Implements all the methods of ListltEgt
...
a1
a2
an-1
a0
19LinkedList (contd)
interface List
interface Iterator
interface ListIterator
- Additional methods specific to LinkedList
void addFirst (E obj) void addLast (E obj)
E getFirst () E getLast () E removeFirst
() E removeLast ()
20 ArrayList vs. LinkedList
- Implements a list as an array
- Provides random access to the elements
- - Inserting and removing elements requires
shifting of subsequent elements - - Needs to be resized when runs out of space
- Implements a list as a doubly-linked list with a
header node - - No random access to the elements needs to
traverse the list to get to the - i-th element
- Inserting and removing elements is done by
rearranging the links no shifting - Nodes are allocated and released as necessary
21ArrayList vs. LinkedList (contd)
22ArrayList vs. LinkedList (contd)
for (int i 0 i lt list.size() i)
Object x list.get (i) ...
Iterator iter list.iterator ( ) while
(iter.hasNext ( )) Object x iter.next
( ) ...
for (Object x list) ...
Works well for an ArrayList ? O(n) inefficient
for a LinkedList ? O(n2)
Work well for both an ArrayList and a LinkedList
? O(n)
23Stacks
- 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.StackltEgt class
24Stacks (contd)
Stack
25StackltEgt Methods
Stack
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
26Queues
- 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)
27Queues (contd)
interface Queue
LinkedList
28QueueltEgt Methods
interface Queue
LinkedList
boolean isEmpty () boolean add (E obj) E
remove () E peek ()
Returns the first element without removing it
from the queue
29Queues (contd)
QueueltMessagegt q new
LinkedListltMessagegt ()
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
30Priority 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)
31Priority Queues (contd)
interface Queue
PriorityQueue
- The same methods as in Queue isEmpty, add,
remove, peek.
32PriorityQueueltEgt 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 25). - Both add and remove methods run in O(log
n) time peek runs in O(1) time.
33Sets
- 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
34Sets (contd)
interface Iterator
interface Collection
interface Set
Methods of SetltEgt are the same as methods of
CollectionltEgt
Sets semantics are different from Collection (no
duplicates), but Set does not add any new methods.
35TreeSetltEgt
interface Set
- Works with Comparable objects (or takes a
comparator as a parameter) - Implements a set as a Binary Search Tree (Chapter
23) - contains, add, and remove methods run in O(log n)
time - Iterator returns elements in ascending order
36HashSetltEgt
interface Set
- Works with objects for which reasonable hashCode
and equals methods are defined - Implements a set as a hash table (Chapter
24) - contains, add, and remove methods run in O(1)
time - Iterator returns elements in no particular order
37Maps
- 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
38Maps (contd)
- java.util
- Map interface
- TreeMap
- HashMap
interface Map
39MapltK, Vgt Methods
interface Map
boolean isEmpty () int size () V get (K
key) V put (K key, V value) V remove (K
key) boolean containsKey (Object key)
SetltKgt keySet ()
Returns the set of all keys
40TreeMapltK,Vgt
interface Map
- Works with Comparable keys (or takes a comparator
as a parameter) - Implements the key set as a Binary Search Tree
- containsKey, get, and put methods run in O(log n)
time
41HashMapltK,Vgt
interface Map
- Works with keys for which reasonable hashCode and
equals methods are defined - Implements the key set as a hash table
- containsKey, get, and put methods run in O(1) time
42Example
- traversing all key-value pairs in a map
import java.util. ... MapltInteger,
Stringgt presidents new
TreeMapltInteger, Stringgt () presidents.put
(1, George Washington) ... for (Integer
key presidents.keySet() ) String
name presidents.get (key)
System.out.println (key " " name)
43Review
- 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.
44Review (contd)
- 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?
45Review (contd)
- 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.
46Review (contd)
- 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?