Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

Object-Oriented Programming

Lecture 8 – Collections Framework

Ralph Tambala

MUST . CSIT

Lecture 8 1 / 24
Outline
1 Overview
Collections Framework
Lists and Sets
Stacks and Queues
Maps
2 The Collection Interface
3 Linked Lists
List Iterators
4 Sets
Hash Table Concept
Tree Concept
Iterators and Sets
5 Maps
6 Additional Info
Lecture 8 2 / 24
Overview Collections Framework

Collections Framework

In this lecture, you will learn about the Java collection framework, a
hierarchy of interface types and classes for collecting objects.

We will take a closer look at the following collections:


Linked Lists
Sets
Maps

Collections are used when you need to organize multiple objects in your
program, you can place them into a collection.

A collection groups together elements and allows them to be accessed and


retrieved later.

Lecture 8 3 / 24
Overview Collections Framework

Collections Framework

Each collection class implements an interface from a hierarchy.


Each class is designed for a specific type of storage.

Figure 1: Collections framework

Each interface type is implemented by one or more classes.

Lecture 8 4 / 24
Overview Lists and Sets

Lists and Sets


A list is a collection that maintains the order of its elements.
ArrayList – Stores a list of items in a dynamically sized array
LinkedList – Allows speedy insertion and removal of items from the
list

Figure 2: Ordered vs unordered

A set is an unordered collection of unique elements.


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
Lecture 8 5 / 24
Overview Stacks and Queues

Stacks and Queues


Another way of gaining efficiency in a collection is to reduce the number of
operations available.
Two examples of such collections are:
Stack
◦ Remembers the order of its elements, but it does not allow you to
insert elements in every position
◦ You can only add and remove elements at the top
Queues
◦ Add items to one end (the tail)
◦ Remove them from the other end (the head)
◦ Example: A line of people waiting for a bank teller

Figure 3: Stack (left) vs queue (right)

Lecture 8 6 / 24
Overview Maps

Maps
A map keeps associations between key and value objects.
A good example is barcode keys and books.

Keys
◦ Provides an easy way to represent an object (such as a numeric bar
code, or a Student Identification Number)
Values
◦ The actual object that is associated with the key
Lecture 8 7 / 24
The Collection Interface

The Collection Interface


The Collection interface (shown in Figure 1) is used to pass around
collections of objects where maximum generality is desired. For example,
by convention all general-purpose collection implementations have a
constructor that takes a Collection argument.
List, Queue and Set are specialized interfaces that inherit from the
Collection interface. This means that they all share the commonly used
methods.

Lecture 8 8 / 24
The Collection Interface

The Collection Interface

Lecture 8 9 / 24
Linked Lists

Linked Lists

Linked lists use references to maintain an ordered lists of ‘nodes’


The ‘head’ of the list references the first node
Each node has a value and a reference to the next node

Linked lists can be used to implement List interface and Queue interface
as shown in Figure 1.

Lecture 8 10 / 24
Linked Lists

Linked Lists
Important methods

Table 2 lists some of the important methods in Linked List class.

Lecture 8 11 / 24
Linked Lists List Iterators

List Iterators

When traversing a LinkedList, use a ListIterator to keep track of


where you are in the list.
1 LinkedList < String > employeeNames = . . .;
2 ListIterator < String > iter = employeeNames . listIterator ()

Think of an iterator as pointing between two elements (think of cursor in


word processor)

Note that the generic type for the ListIterator must match the generic
type of the LinkedList. In the example above, the generic type we have
used is String.

Lecture 8 12 / 24
Linked Lists List Iterators

Iterator and ListIterator Methods (1)


Iterators allow you to move through a list easily. Similar to an index
variable for an array.

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
Lecture 8 13 / 24
Linked Lists List Iterators

Iterator and ListIterator Methods (2)

In a while loop:
1 while ( iterator . hasNext () ) {
2 String name = iterator . next () ;
3 // Do something with name
4 }

In a for-each loop:
1 for ( String name : employeeNames )
2 {
3 // Do something with name
4 }

Lecture 8 14 / 24
Sets

Sets

A set is an unordered collection which does not support duplicate


elements.
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
(as shown in Figure 1).
◦ HashSet: Stores data in a hash table.
◦ TreeSet: Stores data in a binary tree.
◦ Both implementations arrange the set elements so that finding, adding,
and removing elements is efficient.

Lecture 8 15 / 24
Sets Hash Table Concept

Sets
Hash Table Concept

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
(called a hash function) to compute their integer values.

Lecture 8 16 / 24
Sets Tree Concept

Sets
Tree Concept (1)

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”.

Lecture 8 17 / 24
Sets Tree Concept

Sets
Tree Concept (2)

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

Lecture 8 18 / 24
Sets Iterators and Sets

Sets
Iterators and Sets

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
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
1 I t e r a t o r <S t r i n g > i t e r = names . i t e r a t o r ( ) ;
1 I t e r a t o r <S t r i n g > i t e r = names . i t e r a t o r ( ) ;
2 w h i l e ( i t e r . hasNext ( ) )
2 f o r ( S t r i n g name : names )
3 {
3 {
4 String x = i t e r . next () ;
4 // Some c o d e
5 // Some c o d e
5 }
6 }

Listing 1: While loop Listing 2: For-each loop

Lecture 8 19 / 24
Sets Iterators and Sets

Sets
Important methods (1)

Table 4 lists some of the important methods in HashSet and TreeSet


classes.

Lecture 8 20 / 24
Sets Iterators and Sets

Sets
Important methods (2)

Lecture 8 21 / 24
Maps

Maps
A map allows you to associate elements from a key set with elements from
a value collection.
The HashMap and TreeMap classes both implement the Map interface.
Use a map to look up objects by using a key.
The key “unlocks” the “data” (value). A map is like a mathematical
function mapping between two sets.

Lecture 8 22 / 24
Maps

Maps
Basic methods

A map has the form Map<K, V> where:


K: specifies the type of keys maintained in this map.
V: defines the type of mapped values.
The following are the most common used methods provided by Map
interface:
clear: Removes all the elements from the map.
containsKey: Returns true if the map contains the requested key.
containsValue: Returns true if the map contains the requested value.
equals: Compares an Object with the map for equality.
get: Retrieve the value of the requested key.
entrySet: Returns a Set view of the mappings contained in this map.
keySet: Returns a Set that contains all keys of the map.
put: Adds the requested key-value pair in the map.
remove: Removes requested key and its value from map, if the key exists.
size: Returns the number of key-value pairs currently in the map.
Lecture 8 23 / 24
Additional Info

Additional Info

Some may find these articles useful –


◦ Java List Collection Tutorial and Examples
◦ Java Map

Lecture 8 24 / 24

You might also like