0% found this document useful (0 votes)
28 views16 pages

C175 Lecture 10 - Collections

The document discusses the Java Collections Framework which provides classes for organizing groups of objects into collections. It describes common collection interfaces like List, Set, and Map. Lists maintain element order while Sets do not, and Maps associate keys with values. Specific classes implement these interfaces, with tradeoffs between storage and performance of different operations. Stacks and Queues provide further optimizations by restricting allowed operations.

Uploaded by

KELVIN MAIMU
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views16 pages

C175 Lecture 10 - Collections

The document discusses the Java Collections Framework which provides classes for organizing groups of objects into collections. It describes common collection interfaces like List, Set, and Map. Lists maintain element order while Sets do not, and Maps associate keys with values. Specific classes implement these interfaces, with tradeoffs between storage and performance of different operations. Stacks and Queues provide further optimizations by restricting allowed operations.

Uploaded by

KELVIN MAIMU
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

THE JAVA

COLLECTIONS
FRAMEWORK

1.  An Overview of the Java Collections Framework


2.  Linked Lists
3.  Sets
4.  Maps
5.  Stacks Queues and Priority Queues
6.  Stack and Queue Applications

Page 2

1
Java Collections Framework

1.  When you need to organize multiple objects in your


program, you can place them into a collection
2.  The ArrayList class that was introduced in Chapter
6 is one of many collection classes that the standard
Java library supplies
3.  Each interface type is implemented by one or
more classes
A collection groups together
elements and allows them to be
accessed and retrieved later

Page 3

Collections Framework Diagram

l  Each collection class implements an interface from a


hierarchy
•  Each class is designed for a
specific type of storage

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

Lists and Sets


l  Unordered Sets

• 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

•  Barcode keys and books


9 780470 105542 9 780470 509481

ISBN 978-0-470-10555-9 ISBN 978-0-471-79191-1 ISBN 978-0-470-38329-2

9 00 00 9 00 00 9 00 00

9 780470 105559 9 780471 791911 9 780470 383292

A map keeps associations


between key and value objects.

l  Keys Values

•  Provides an easy way to represent an object (such as


a Figure 5 A Map from Bar Codes to Books

numeric bar code, or a Student Identification Number)


l  Values
•  The actual object that is associated with the key
Page 8

4
The Collection Interface (1)

l  List, Queue and Set are specialized interfaces that


inherit from the Collection interface
•  All share the following commonly used methods

Page 9

The Collection Interface (2)

Page 10

5
15.2 Linked Lists 673

15.2.1 T he Structure of Linked Lists


To understand the inefficiency of arrays
and the need for a more efficient data
structure, imagine a program that main-
tains a sequence of employee names. If an
employee leaves the company, the name
must be removed. In an array, the hole 15.2 Linked Lists 673
in the sequence needs to be closed up by
moving all objects that come after it. Con-
15.2.1
versely, suppose an employee T heinStructure of Linked Lists
is added
15.2 Linked Lists
the middle of the sequence. Then all names
following the new hireTomust be moved
understand the inefficiency oflinked
Each node in a arrays
list is connected to the
toward the end. Movingand a large
thenumber of a neighboring
need for more efficient
nodes. data
elements can involve a substantial amount
A linked list consists structure, imagine a program that main-
of processing time. A linked list structure
of a number of tains a sequence of employee names. If an
avoids this movement.
nodes, each of which
has a reference to l  Linked lists use references to maintain an ordered
employee
A linked list uses a sequence of leaves
nodes. the company,
A node the name
is an object that stores an element
the next node. must be removed. Insequence
an array,(see
theFigure
hole 6).
lists of ‘nodes’ in the sequence needs to be closed up by
and references to the neighboring nodes in the

•  The ‘head’ of the


moving all objects thatthe
list references come after node
first it. Con-
versely, suppose an employee is added in
•  Each node has athevalue
middleand
Tom of theasequence.
referenceThen to
Diana the next node
all names Harry
Figure 6 following the new hire must be moved Each 15.2 node
Linked
in aLists
linked 673
list is connected to the
A Linked List toward the end. Moving a large number of neighboring nodes.
elements
15.2.1 can T heinvolve a substantial
Structure of Linked amount
Lists
A linked list consists
of a number of of processing time. A linked list structure
When you insert a new node into a linked
To understand list, only of
the inefficiency thearrays
neighboring node references
nodes, each of which avoids this movement.
• 
need
They
has
to
a
be updated
can be usedtains
reference
the next node.
to
and the
(see Figure 7).need for a more efficient data
to aimplement
A linked
structure, list
imagine uses
a a sequence
program that of nodes. A node is an object that stores an element
main-

•  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

•  Find the element to remove


lists allow speedy insertion and removal, but element access can be slow.

•  Remap neighbor’s references


Figure 8
Figure 8
Removing
Removing aa Tom Tom Diana Diana Harry Harry

•  Visiting all elements in order


Node
Node from
from aa
Linked List
Linked List

l  Inefficient Operations Each instance variable is declared just like


•  Random access other variables we have used.

Page 12

6
LinkedList: Important Methods

Page 13

Generic Linked Lists

l  The Collection Framework uses Generics


•  Each list is declared with a type field in < > angle brackets

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()

l  Use an iterator to:


•  Access elements inside a linked list
•  Visit other than the first and the last nodes

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”);

q  Note that the generic type for the listIterator


must match the generic type of the LinkedList

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

Iterators and Loops


l  Iterators are often used in while and “for-each” loops
hasNext returns true if there is a next element
next returns a reference to the value of the next element
while (iterator.hasNext())
{
String name = iterator.next();
// Do something with name for (String name : employeeNames)
} {
// Do something with name
}

• Where is the iterator in the “for-next” loop?


•  Iterators are used ‘behind the scenes’
Page 18

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

The HashSet and TreeSet classes both


implement the Set interface.

Page 22

11
Sets

l  HashSet: Stores data in a Hash Table


l  TreeSet: Stores data in a Binary Tree
l  Both implementations arrange the set
elements so that finding, adding, and
removing elements is efficient

Set implementations arrange the elements so


that they can locate them quickly

Page 23

Hash Table Concept


l  Set elements are grouped into smaller collections of
elements that share the same characteristic
•  It is usually based on the result of a mathematical
calculation on the contents that results in an integer value
•  In order to be stored in a hash table, elements must have a
method to compute their integer values

100

101

102

Page 24

12
hashCode

•  The method is called hashCode


•  If multiple elements have the same hash code (so-
called clash), they are stored in a LinkedList

•  The elements must also have an equals method


for checking whether an element equals another
like:
•  String, Integer, Point, Rectangle, Color, and all collection
classes
Set<String> names = new HashSet<String>();

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

•  In order to use a TreeSet, it must be possible to compare


the elements and determine which one is “larger”

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

Iterators and Sets


l  Iterators are also used when processing sets
• hasNext returns true if there is a next element
• next returns a reference to the value of the next element
• add via the iterator is not supported for TreeSet and HashSet
Iterator<String> iter = names.iterator();
while (iter.hasNext())
{ for (String name : names)
String name = iter.next(); {
// Do something with name // Do something with name
} }

•  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

Working With Sets (2)

Page 30

15
SpellCheck.java (1)

Page 31

SpellCheck.java (2)

Page 32

16

You might also like