C175 Lecture 10 - Collections
C175 Lecture 10 - Collections
COLLECTIONS
FRAMEWORK
Page 2
1
Java Collections Framework
Page 3
Page 4
2
Lists and Sets
l Ordered Lists
• ArrayList
• Stores a list of items in a dynamically sized array
• LinkedList
• Allows speedy insertion and removal of items from the list
A list is a collection that maintains the
order of its elements.
Page 5
• HashSet
• Uses hash tables to speed up finding, adding, and removing
elements
• TreeSet
• Uses a binary tree to speed up finding, adding, and
removing elements
A set is an unordered collection of
unique elements.
Page 6
3
Stacks and Queues
15.1 An Overview of the Collections Framework 671
l Another way of gaining efficiency in a collection is
to reduce the number of operations available
l Two examples are:
• Stack
• Remembers the order of its elements, but it does not
allow you toFigure
insert2 elements
A List of Booksin every position
Figure 3 A Set of Books Figure 4 A Stack of Books
• You can only add and remove elements at the top
However, in many applications, you don’t really care about the order of the ele-
• Queue ments in a collection. Consider a mail-order dealer of books. Without customers
browsing the shelves, there is no need to order books by topic. Such a collection
• Add items to one end (the tail) without an intrinsic order is called a set—see Figure 3.
• Remove themA setfrom the other
is an unordered
Because a set does not track the order of the elements, it can arrange them in a
end (the head)
way that speeds up the operations of finding, adding, and removing elements. Com-
•
collection of unique
Example: Aelements.
line of peopleputer waiting forhave
scientists a bank teller
invented mechanisms for this purpose. The Java library provides
classes that are based on two such mechanisms (called hash tables and binary search
trees). You will learn in this chapter how to choose between them.
Another way of gaining efficiency in a collection
Page is
7 to reduce the number of opera-
tions. A stack remembers the order of its elements, but it does not allow you to insert
elements in every position. You can add and remove elements only at the top—see
Figure 4.
In a queue, you add items to one end (the tail) and remove them from the other end
(the head). For example, you could keep a queue of books, adding required reading at
the tail and taking a book from the head whenever you have time to read another one.
We will discuss stacks and queues in Section 15.5.
A map keeps
Finally, a map manages associations between keys and values. Every key in the
associations map has an associated value. The map stores the keys, values, and the associations
between key and between them. For an example, consider a library that puts a bar code on each book.
value objects.
The program used to check books in and out needs to look up the book associated
with each bar code. A map associating bar codes with books can solve this problem—
see Figure 5. We will discuss maps in Section 15.4.
l AMaps
map stores keys, values, and the associations
between them Keys
• Example:
ISBN 978-0-470-10554-2 ISBN 978-0-470-50948-1
9 00 00 9 00 00
9 00 00 9 00 00 9 00 00
l Keys Values
4
The Collection Interface (1)
Page 9
Page 10
5
15.2 Linked Lists 673
• A List Interface
sequence of employee names. If an
and references to the neighboring
employee leaves the company, the name
nodes in the sequence (see Figure 6).
• A Queue Interface
must be removed. In an array, the hole
in the sequence needs to be closed up by
Tom moving all objects that
Dianacome after it. Con- Harry
versely, suppose an employee is added in
the middle of the sequence. Then all names
Tom Diana Harry
following the new hire must be moved Each node in a linked list is connected to the
Figure 6 Page 11
toward the end. Moving a large number of neighboring nodes.
A elements
Linked List
can involve a substantial amount
Figure 7 A linked list consists of processing time. A linked list structure
of a number of
Insertingnodes,
a each of which avoids this movement. Romeo
Node intohas a reference to
a A linked list uses a sequence of nodes. A node is an object that stores an element
the next node. When you insert a new node intoina the
and references to the neighboring nodes linked list,(see
sequence only the6).neighboring
Figure node references
Linked List
need to be updated (see Figure 7).
The same is true when you remove a nodeTom (see Figure 8).Diana
What’s the catch?
Harry Linked
lists allow speedy insertion and6removal, but element access can be slow.
Figure
A Linked List
Tom Diana Harry
Linked Lists Operations When you insert a new node into a linked list, only the neighboring node references
need to be updated (see Figure 7).
Figure 8
Removing a Tom Diana Harry
l Efficient
Node from aOperations
Figure 7
• Insertion of a node
Tom Diana Harry
Linked List Inserting a Romeo
Node into a
• Find the elements it goes
Linked List between
• Remap the references
Figure 7
Inserting a Romeo
Node into a
The same
Linked List is true when you remove a node (see Figure 8). What’s the catch? Linked
lists allow speedy insertion and removal, but element access can be slow.
• Removal of a node The same is true when you remove a node (see Figure 8). What’s the catch? Linked
Page 12
6
LinkedList: Important Methods
Page 13
LinkedList<String> employeeNames = . . .;
LinkedList<String>
LinkedList<Employee>
Page 14
7
List Iterators
l When traversing a LinkedList, use a ListIterator
• Keeps track of where you are in the list.
LinkedList<String> employeeNames = . . .;
ListIterator<String> iter = employeeNames.listIterator()
Page 15
Using Iterators
l Think of an iterator as pointing between two
elements (think of cursor in word processor)
ListIterator<String> iter = myList.listIterator()
iterator.next();
iterator.add(“J”);
Page 16
8
Iterator and ListIterator Methods
l Iterators allow you to move through a list easily
• Similar to an index variable for an array
Page 17
9
Adding and Removing with Iterators
l Adding iterator.add("Juliet");
• A new node is added AFTER the Iterator
• The Iterator is moved past the new node
l Removing
• Removes the object that was returned with the last call to next
or previous
• It can be called only once after next or previous
• You cannot call it immediately after a call to add.(why?)
while (iterator.hasNext())
{
String name = iterator.next();
If you call the remove if (condition is true for name)
method improperly, it throws an {
IllegalStateException. iterator.remove();
}
}
Page 19
ListDemo.java (1)
l Illustrates adding, removing and printing a list
Page 20
10
ListDemo.java (2)
Page 21
15.3 Sets
l A set is an unordered collection
• It does not support duplicate elements
l The collection does not keep track of the order in
which elements have been added
• Therefore, it can carry out its operations more efficiently
than an ordered collection
Page 22
11
Sets
Page 23
100
101
102
Page 24
12
hashCode
Page 25
Tree Concept
l Set elements are kept in sorted order
• Nodes are not arranged in a linear sequence
but in a tree shape
Page 26
13
TreeSet
• Use TreeSet for classes that implement the
Comparable interface
• String and Integer, for example
• The nodes are arranged in a ‘tree’ fashion so that
each ‘parent’ node has two child nodes.
• The node to the left always has a ‘smaller’ value
• The node to the right always has a ‘larger’ value
Set<String> names = new TreeSet<String>();
Page 27
• Note that the elements are not visited in the order in which you
inserted them.
• They are visited in the order in which the set keeps them:
• Seemingly random order for a HashSet
• Sorted order for a TreeSet
Page 28
14
Working With Sets (1)
Page 29
Page 30
15
SpellCheck.java (1)
Page 31
SpellCheck.java (2)
Page 32
16