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

Lecture 9-10

Java Collection Framework

Kulbayeva Aliya Kayratovna, McS of Science


a.kulbayeva@iitu.edu.kz
Outline

´ An Overview of the Java Collections Framework


´ Linked Lists
´ Sets
´ Maps
´ Stacks Queues and Priority Queues
´ Stack and Queue Applications
iitulogo.12b10e7a
0eb7.png
OBJECTIVES

● To learn how to use the collection classes supplied in the Java library
● To use iterators to traverse collections
● To choose appropriate collections for solving programming problems
● To study applications of stacks and queues

iitulogo.12b10e7a
0eb7.png
Java Collections Framework

● The Java Collections Framework is a collection of


interfaces and classes which helps in storing and
processing the data efficiently. This framework has
several useful classes which have tons of useful
functions which makes a programmer task super easy

iitulogo.12b10e7a
0eb7.png
Java Collections Framework

● When you need to organize multiple objects in your program, you can
place them into a collection
● The ArrayList class as an example. It is one of many collection classes
that the standard Java library supplies
● Each interface type is implemented by one or more classes

iitulogo.12b10e7a
0eb7.png
Java Collections Framework

A collections framework is a unified architecture for representing and


manipulating collections.
´ Interfaces − These are abstract data types that represent collections.
Interfaces allow collections to be manipulated independently of the
details of their representation.
´ Implementations − These are the concrete implementations of the
collection interfaces.
´ Algorithms − Methods that perform useful computations, (searching
and sorting), on objects that implement collection interfaces.
Algorithms said to be polymorphic: the same method can be used on
many different implementations of the appropriate collection interface.
iitulogo.12b10e7a
0eb7.png
Collections Framework hierarchy

● Each collection class


implements an interface
from a hierarchy

● Each class is designed for a


specific type of storage

iitulogo.12b10e7a
0eb7.png
Java Collections Framework

Java Collection Framework supports two types of


containers:
- collections: for storing a collection of elements
- map: for storing key/value pairs

iitulogo.12b10e7a
0eb7.png
The collection interfaces

´ The Collection Interface


This enables you to work with groups of objects; it is at the top of the
collections hierarchy.
´ The List Interface
This extends Collection and an instance of List stores an ordered
collection of elements.
´ The Set
This extends Collection to handle sets, which must contain unique
elements.
´ The SortedSet
This extends Set to handle sorted sets.
iitulogo.12b10e7a
0eb7.png
The collection interfaces

´ The Map
This maps unique keys to values.
´ The Map.Entry
This describes an element (a key/value pair) in a map. This is an inner
class of Map.
´ The SortedMap
This extends Map so that the keys are maintained in an ascending order.
´ Iterator
Iterator enables you to cycle through a collection, obtaining or
removing elements.
iitulogo.12b10e7a
0eb7.png
The collection interfaces
The Collection interface is the foundation upon which the collections
framework is built. It declares the core methods that all collections will
have.
Methods and Description:
´ boolean add(Object obj)
Adds obj to the invoking collection. Returns true if obj was added to the
collection. Returns false if obj is already a member of the collection, or if
the collection does not allow duplicates.
´ boolean addAll(Collection c)
Adds all the elements of c to the invoking collection. Returns true if the
operation succeeds (i.e., the elements were added). Otherwise, returns
false. iitulogo.12b10e7a
0eb7.png
The collection interfaces
´ void clear( )
Removes all elements from the invoking collection.
´ boolean contains(Object obj)
Returns true if obj is an element of the invoking collection. Otherwise, returns false.
´ boolean containsAll(Collection c)
Returns true if the invoking collection contains all elements of c. Otherwise, returns
false.
´ boolean equals(Object obj)
Returns true if the invoking collection and obj are equal. Otherwise, returns false.
´ int hashCode( )
Returns the hash code for the invoking collection.
´ boolean isEmpty( )
Returns true if the invoking collection is empty. Otherwise, returns false.
´ Iterator iterator( )
Returns an iterator for the invoking collection.
iitulogo.12b10e7a
0eb7.png
The collection interfaces
´ boolean remove(Object obj)
Removes one instance of obj from the invoking collection. Returns true if the element was
removed. Otherwise, returns false.
´ boolean removeAll(Collection c)
Removes all elements of c from the invoking collection. Returns true if the collection
changed.
´ boolean retainAll(Collection c)
Removes all elements from the invoking collection except those in c. Returns true if the
collection changed.
´ int size( )
Returns the number of elements held in the invoking collection.
´ Object[ ] toArray( )
´ Returns an array that contains all the elements stored in the invoking collection. The array
elements are copies of the collection elements.
´ Object[ ] toArray(Object array[ ])
´ Returns an array containing only those collection elements whose type matches that of array
iitulogo.12b10e7a
0eb7.png
The List Interface

The List interface extends Collection and declares the behavior of a


collection that stores a sequence of elements.

● Elements can be inserted or accessed by their position in the list, using a


zero-based index.
● A list may contain duplicate elements.

iitulogo.12b10e7a
0eb7.png
Example

iitulogo.12b10e7a
0eb7.png
Lists and Sets

● Ordered List

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

iitulogo.12b10e7a
0eb7.png
Lists and Sets

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

iitulogo.12b10e7a
0eb7.png
Stacks and Queues
´ Another way of gaining efficiency in a collection is to reduce
the number of operations available
´ Two examples 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

´ Queue
´ 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
iitulogo.12b10e7a
0eb7.png
In a queue, you add items to one end (the tail) and remove them from
(the head). For example, you could keep a queue of books, adding requ
the tail and taking a book from the head whenever you have time to rea
We will discuss stacks and queues in Section 15.5.
A map keeps
Finally, a map manages associations between keys and values. Ev
associations map has an associated value. The map stores the keys, values, and th
between key and between them. For an example, consider a library that puts a bar code o
Maps value objects.
The program used to check books in and out needs to look up the bo
with each bar code. A map associating bar codes with books can solve t
see Figure 5. We will discuss maps in Section 15.4.

´ A map stores keys, values, and the associations between them


´ Example: Keys ISBN 978-0-470-10554-2
90000
ISBN 978-0-470-50948-1
90000

´ Barcode keys and books ISBN 978-0-470-10555-9


90000
9 780470 105542

ISBN 978-0-471-79191-1
90000
9 780470 509481

ISBN 978-0-470-38329-2

9 780470 105559 9 780471 791911 9 780470 383292

A map keeps associations


between key and value objects.

´ Keys Values

´ Provides an easy way to represent an objectFigure


(such as a numeric bar
5 A Map from Bar Codes to Books

code)
´ Values
´ The actual object that is associated with the key
iitulogo.12b10e7a
0eb7.png
The Collection Interface (1)
● List, Queue and Set are specialized interfaces that inherit from the Collection interface
○ All share the following commonly used methods

iitulogo.12b10e7a
0eb7.png
The Collection Interface (2)

iitulogo.12b10e7a
0eb7.png
in the sequence needs to be closed up by
moving all objects that come after it. Con-
versely, suppose an employee is added in
the middle of the sequence. Then all names
following the new hire must be moved Each node in a linked list is connected to the
Linked Lists
toward the end. Moving a large number of neighboring nodes.
elements can involve a substantial amount
list consists
mber of of processing time. A linked list structure
each of which avoids this movement.
ference to ● Linked listslist
A linked use references
uses tonodes.
a sequence of maintain
A nodean
is ordered listsstores
an object that of ‘nodes’
an element
t node.
and references○to theThe ‘head’ of
neighboring theinlist
nodes the references the first
sequence (see Figure 6). node
○ Each node has a value and a reference to the next node

Tom Diana Harry


Figure 6
A Linked List

○ They can be used to implement


■ A list,
When you insert a new node into a linked List Interface
only the neighboring node references
need to be updated (see Figure 7).
■ A Queue Interface
iitulogo.12b10e7a
0eb7.png
Tom Diana Harry
A Linked List

When you insert a new node into a linked list, only the neighboring node references
need to be updated (see Figure 7).

Linked Lists Operations


Figure 7
Inserting a Romeo
Node into a Tom Diana Harry
´ Efficient Operations
Linked List
´ Insertion of a node
´ Find the elements it goes
between The Inserting
same is true when you remove a node (see Figure 8). What’s t
Figure 7
a Romeo
lists Node
allow
´ Remap the references
intospeedy
a insertion and removal, but element access can be
Linked List
´ Removal of a node
´ Find the element The sameto 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.
remove Figure 8
´ Remap neighbor’s
Removing a Tom Diana Harry
referencesNode from
Figure 8 a
Linkedin
´ Visiting all elements List
Removing a
order Tom Diana Harry
Node from a
´ Inefficient Operations Linked List Each instance variable is declarediitulogo.12b10e7a
just like other
´ Random access variables we have used. 0eb7.png
LinkedList:
Important Methods

iitulogo.12b10e7a
0eb7.png
Generic Linked Lists

´ The Collection Framework uses Generics


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

LinkedList<String> employeeNames = . . .;

LinkedList<String>
LinkedList<Employee>

iitulogo.12b10e7a
0eb7.png
List Iterators

q When traversing a LinkedList, use a ListIterator


§ Keeps track of where you are in the list.

LinkedList<String> employeeNames = . . .;
ListIterator<String> iter = employeeNames.listIterator()

q Use an iterator to:


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

iitulogo.12b10e7a
0eb7.png
Using Iterators

● Think of an iterator as pointing between two elements


ListIterator<String> iter = myList.listIterator()

iterator.next();

iterator.add(“J”);

Note that the generic type for the listIterator must match the generic type
of the LinkedList iitulogo.12b10e7a
0eb7.png
Iterator and ListIterator Methods
● Iterators allow you to move through a list easily
○ Similar to an index variable for an array

iitulogo.12b10e7a
0eb7.png
Iterators and Loops
´ 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(); for (String name : employeeNames)
// Do something with name {
} // Do something with name
}

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


´ It is used ‘behind the scenes’ iitulogo.12b10e7a
0eb7.png
Adding and Removing with Iterators
iterator.add("Juliet");
● Adding
○ A new node is added AFTER the Iterator
○ The Iterator is moved past the new node
● 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.

If you call the remove while (iterator.hasNext())


method improperly, it throws an {
IllegalStateException. String name = iterator.next();
if (condition is true for name)
{ iitulogo.12b10e7a
iterator.remove();0eb7.png
}
ListDemo.java (1)
v Illustrates adding, removing and printing a list

iitulogo.12b10e7a
0eb7.png
ListDemo.java (2)

iitulogo.12b10e7a
0eb7.png
The Set Interface

● A Set is a Collection that cannot contain duplicate elements. It models


the mathematical set abstraction.
● The Set interface contains only methods inherited from Collection and
adds the restriction that duplicate elements are prohibited.
● Set has its implementation in various classes like HashSet, TreeSet,
LinkedHashSet.

iitulogo.12b10e7a
0eb7.png
Example

iitulogo.12b10e7a
0eb7.png
Sets
´ A set is an unordered collection

´ It 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.
iitulogo.12b10e7a
0eb7.png
Sets
´ 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

Set implementations arrange the elements


so that they can locate them quickly
iitulogo.12b10e7a
0eb7.png
The SortedSet Interface

The SortedSet interface extends Set and declares the behavior of a set
sorted in an ascending order.

SortedSet have its implementation in various classes like TreeSet.

iitulogo.12b10e7a
0eb7.png
Example

iitulogo.12b10e7a
0eb7.png
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 100
○ In order to be stored in a hash
table, elements must have
101
a method to compute their
integer values

iitulogo.12b10e7a
0eb7.png
hashCode
○ The method is called hashCode

■ If multiple elements have the same hash code, they are stored
in a Linked list

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

iitulogo.12b10e7a
0eb7.png
Tree Concept

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

iitulogo.12b10e7a
0eb7.png
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 up to 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>();

iitulogo.12b10e7a
0eb7.png
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
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
iitulogo.12b10e7a
0eb7.png
Working With Sets (1)

iitulogo.12b10e7a
0eb7.png
Working With Sets (2)

iitulogo.12b10e7a
0eb7.png
SpellCheck.java (1)

iitulogo.12b10e7a
0eb7.png
SpellCheck.java (2)

iitulogo.12b10e7a
0eb7.png

You might also like