Java JavaCollectionsFramework BW

You might also like

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

Object Oriented

1
Programming
Java Collection Framework
13 March 2019
2
Java Collection Framework

• A container is an object that stores


other group of objects, often
referred to as elements.
• JCF supports two types of containers
– Collection: collection of elements
- Map: storing key/value pairs
Java Collection Framework 3
hierarchy
Set: a group of non-duplicate elements
List: an ordered lcollection of elements
Queue: stores objects that are processed in
first-in, first-out fashion
SortedSet TreeSet

Set AbstractSet HashSet LinkedHashSet

Collection AbstractCollection
Vector Stack

List AbstractList
ArrayList

AbstractSequentialList LinkedList
Deque

Queue AbstractQueue PriorityQueue

Interfaces Abstract Classes Concrete Classes


Java Collection Framework 4
hierarchy

An instance of Map represents a group of


objects, each of which is associated with a key.
You can get the object from a map using a key,
and you have to use a key to put the object into
the map.

SortedMap TreeMap

Map AbstractMap HashMap LinkedHashMap

Interfaces Abstract Classes Concrete Classes


5
The Collection Interface
The Collection interface is the root interface
«interface» for manipulating a collection of objects.
java.util.Collection<E>
+add(o: E): boolean Adds a new element o to this collection.
+addAll(c: Collection<? extends E>): boolean Adds all the elements in the collection c to this collection.
+clear(): void Removes all the elements from this collection.
+contains(o: Object): boolean Returns true if this collection contains the element o.
+containsAll(c: Collection<?>):boolean Returns true if this collection contains all the elements in c.
+equals(o: Object): boolean Returns true if this collection is equal to another collection o.
+hashCode(): int Returns the hash code for this collection.
+isEmpty(): boolean Returns true if this collection contains no elements.
+iterator(): Iterator Returns an iterator for the elements in this collection.
+remove(o: Object): boolean Removes the element o from this collection.
+removeAll(c: Collection<?>): boolean Removes all the elements in c from this collection.
+retainAll(c: Collection<?>): boolean Retains the elements that are both in c and in this collection.
+size(): int Returns the number of elements in this collection.
+toArray(): Object[] Returns an array of Object for the elements in this collection.

«interface»
java.util.Iterator<E>
+hasNext(): boolean Returns true if this iterator has more elements to traverse.
+next(): E Returns the next element from this iterator.
+remove(): void Removes the last element obtained using the next method.
6
The Set Interface

• The Set interface extends the Collection


interface. It does not introduce new
methods or constants, but it stipulates
that an instance of Set contains no
duplicate elements. The concrete
classes that implement Set must ensure
that no duplicate elements can be
added to the set. That is no two
elements e1 and e2 can be in the set
such that e1.equals(e2) is true.
7
The Set Interface Hierarchy
«interface»
java.util.Collection<E>

«interface»
java.util.Set<E>
What are 3
concrete
class of the
java.util.AbstractSet<E> «interface»
java.util.SortedSet<E>
java.util.HashSet<E> +first(): E
+HashSet()
+HashSet(c: Collection<? extends E>)
+last(): E
+headSet(toElement: E): SortedSet<E>
+tailSet(fromElement: E): SortedSet<E>
Set
interface?
+HashSet(initialCapacity: int)
+HashSet(initialCapacity: int, loadFactor: float)

«interface»
java.util.NavigableSet<E>
java.util.LinkedHashSet<E>
+LinkedHashSet()
+LinkedHashSet(c: Collection<? extends E>)
+pollFirst(): E
+pollLast(): E HashSet
LinkedHash
+lower(e: E): E
+LinkedHashSet(initialCapacity: int)
+higher(e: E):E
+LinkedHashSet(initialCapacity: int, loadFactor: float)
+floor(e: E): E

Set
+ceiling(e: E): E

java.util.TreeSet<E>
+TreeSet()
+TreeSet(c: Collection<? extends E>) TreeSet
+TreeSet(comparator: Comparator<? super E>)
+TreeSet(s: SortedSet<E>)
8
The AbstractSet Class

• The AbstractSet class is a convenience


class that extends AbstractCollection
and implements Set. The AbstractSet
class provides concrete implementations
for the equals method and the hashCode
method. The hash code of a set is the
sum of the hash code of all the
elements in the set. Since the size
method and iterator method are not
implemented in the AbstractSet class,
AbstractSet is an abstract class.
9
The HashSet Class

• The HashSet class is a concrete class


that implements Set.
• It can be used to store duplicate-
free elements.
• For efficiency, objects added to a
hash set need to implement the
hashCode method in a manner that
properly disperses the hash code.
10
HashSet: Example 1
11
HashSet: Example 2
12
HashSet methods

.add() , addAll()
.remove() , removeAll()
.retainAll()
.contains() – returns boolean
13
LinkedHashSet

• Extends HashSet, used to store


duplicate-free elements.
• Supports an ordering of the elements
– retrieved in the order which they
are inserted into the set.
• HashSet is more efficient that
LinkedHashSet.
14
LinkedHashSet: Example 1
The SortedSet Interface and the 15
TreeSet Class

SortedSet is a subinterface of Set,


which guarantees that the elements in
the set are sorted. TreeSet is a
concrete class that implements the
SortedSet interface.
16
TreeSet: Example 1
The List Interface 17

A set stores non-duplicate elements. To


allow duplicate elements to be stored in a
collection, you need to use a list.
A list can not only store duplicate
elements, but can also allow the user to
specify where the element is stored. The
user can access the element by index.
✓ArrayList
✓LinkedList
✓Vector
The List Interface, cont. 18

«interface»
java.util.Collection<E>

«interface»
java.util.List<E>

+add(index: int, element:E): boolean Adds a new element at the specified index.
+addAll(index: int, c: Collection<? extends E>) Adds all the elements in c to this list at the specified
: boolean index.
+get(index: int): E Returns the element in this list at the specified index.
+indexOf(element: Object): int Returns the index of the first matching element.
+lastIndexOf(element: Object): int Returns the index of the last matching element.
+listIterator(): ListIterator<E> Returns the list iterator for the elements in this list.
+listIterator(startIndex: int): ListIterator<E> Returns the iterator for the elements from startIndex.
+remove(index: int): E Removes the element at the specified index.
+set(index: int, element: E): E Sets the element at the specified index.
+subList(fromIndex: int, toIndex: int): List<E> Returns a sublist from fromIndex to toIndex.
The List Iterator 19

«interface»
java.util.Iterator<E>

«interface»
java.util.ListIterator<E>

+add(o: E): void Adds the specified object to the list.


+hasPrevious(): boolean Returns true if this list iterator has more elements
when traversing backward.
+nextIndex(): int Returns the index of the next element.
+previous(): E Returns the previous element in this list iterator.
+previousIndex(): int Returns the index of the previous element.
+set(o: E): void Replaces the last element returned by the previous or
next method with the specified element.
ArrayList and LinkedList 20

An array is fixed once it is created. If your application


does not require insertion or deletion of elements, the
most efficient data structure is the array.
The ArrayList class and the LinkedList class are
concrete implementations of the List interface.
Which of the two classes you use depends on your
specific needs. If you need to support random access
through an index without inserting or removing
elements from any place other than the end, ArrayList
offers the most efficient collection.
If, however, your application requires the insertion or
deletion of elements from any place in the list, you
should choose LinkedList. A list can grow or shrink
dynamically.
java.util.ArrayList 21

«interface»
java.util.Collection<E>

«interface»
java.util.List<E>

java.util.ArrayList<E>

+ArrayList() Creates an empty list with the default initial capacity.


+ArrayList(c: Collection<? extends E>) Creates an array list from an existing collection.
+ArrayList(initialCapacity: int) Creates an empty list with the specified initial capacity.
+trimToSize(): void Trims the capacity of this ArrayList instance to be the
list's current size.
java.util.LinkedList 22

«interface»
java.util.Collection<E>

«interface»
java.util.List<E>

java.util.LinkedList<E>

+LinkedList() Creates a default empty linked list.


+LinkedList(c: Collection<? extends E>) Creates a linked list from an existing collection.
+addFirst(o: E): void Adds the object to the head of this list.
+addLast(o: E): void Adds the object to the tail of this list.
+getFirst(): E Returns the first element from this list.
+getLast(): E Returns the last element from this list.
+removeFirst(): E Returns and removes the first element from this list.
+removeLast(): E Returns and removes the last element from this list.
23
ArrayList: Example
24
ArrayList: Example 2
25
ArrayList: Example 3 - sort
26
ArrayList: Example 4 - Iterator
27
LinkedList
28
ArrayList vs. LinkedList
29
The Vector Class

In Java 2, Vector is the same as ArrayList,


except that Vector contains the
synchronized methods for accessing and
modifying the vector. None of the new
collection data structures introduced so
far are synchronized. If synchronization is
required, you can use the synchronized
versions of the collection classes.
30
The Vector and Stack Classes

The Java Collections Framework was


introduced with Java 2. Several data
structures were supported prior to Java 2.
Among them are the Vector class and the
Stack class. These classes were
redesigned to fit into the Java Collections
Framework, but their old-style methods
are retained for compatibility.
31
Vector

• Vector implements a dynamic array. It is


similar to ArrayList, but with two
differences −
• Vector is synchronized.
• Vector contains many legacy methods that are
not part of the collections framework.
• Vector proves to be very useful if you don't
know the size of the array in advance or
you just need one that can change sizes
over the lifetime of a program.
• Note: By default, vector doubles its size.
The Vector Class, cont. 32

«interface»
java.util.List<E>

java.util.Vector<E>
+Vector() Creates a default empty vector with initial capacity 10.
+Vector(c: Collection<? extends E>) Creates a vector from an existing collection.
+Vector(initialCapacity: int) Creates a vector with the specified initial capacity.
+Vector(initCapacity:int, capacityIncr: int) Creates a vector with the specified initial capacity and increment.
+addElement(o: E): void Appends the element to the end of this vector.
+capacity(): int Returns the current capacity of this vector.
+copyInto(anArray: Object[]): void Copies the elements in this vector to the array.
+elementAt(index: int): E Returns the object at the specified index.
+elements(): Enumeration<E> Returns an enumeration of this vector.
+ensureCapacity(): void Increases the capacity of this vector.
+firstElement(): E Returns the first element in this vector.
+insertElementAt(o: E, index: int): void Inserts o to this vector at the specified index.
+lastElement(): E Returns the last element in this vector.
+removeAllElements(): void Removes all the elements in this vector.
+removeElement(o: Object): boolean Removes the first matching element in this vector.
+removeElementAt(index: int): void Removes the element at the specified index.
+setElementAt(o: E, index: int): void Sets a new element at the specified index.
+setSize(newSize: int): void Sets a new size in this vector.
+trimToSize(): void Trims the capacity of this vector to its size.
33
The Stack Class
The Stack class represents a last-in-
first-out stack of objects. The
elements are accessed only from the
java.util.Vector<E> top of the stack. You can retrieve,
insert, or remove an element from
the top of the stack.
java.util.Stack<E>

+Stack() Creates an empty stack.


+empty(): boolean Returns true if this stack is empty.
+peek(): E Returns the top element in this stack.
+pop(): E Returns and removes the top element in this stack.
+push(o: E) : E Adds a new element to the top of this stack.
+search(o: Object) : int Returns the position of the specified element in this stack.
34
Vector: Example 1
35
ArrayList vs. Vector
Queues and Priority Queues 36

A queue is a first-in/first-out data


structure. Elements are appended to the
end of the queue and are removed from
the beginning of the queue. In a priority
queue, elements are assigned priorities.
When accessing elements, the element
with the highest priority is removed
first.
The Queue Interface 37

«interface»
java.util.Collection<E>

«interface»
java.util.Queue<E>

+offer(element: E): boolean Inserts an element to the queue.


+poll(): E Retrieves and removes the head of this queue, or null
if this queue is empty.
+remove(): E Retrieves and removes the head of this queue and
throws an exception if this queue is empty.
+peek(): E Retrieves, but does not remove, the head of this queue,
returning null if this queue is empty.
+element(): E Retrieves, but does not remove, the head of this queue,
throwing an exception if this queue is empty.
The PriorityQueue Class 38

«interface»
java.util.Queue<E>

java.util.PriorityQueue<E>
+PriorityQueue() Creates a default priority queue with initial capacity 11.
+PriorityQueue(initialCapacity: int) Creates a default priority queue with the specified initial
capacity.
+PriorityQueue(c: Collection<? extends Creates a priority queue with the specified collection.
E>)
+PriorityQueue(initialCapacity: int, Creates a priority queue with the specified initial
comparator: Comparator<? super E>) capacity and the comparator.
39
PriorityQueue

• Prioritization issues:
• Print jobs – faculty or staff first?
• Emergency room scheduling – fire
(burnt) or broken finger patients first?
• Which product can be discontinued
due to poor sales output?
40
PriorityQueue: methods

Method/ Description
Constructor
PriorityQueue<E>() constructs new empty queue
add(E value) adds value in sorted order
clear() removes all elements
iterator() returns iterator over elements
offer() adds value
peek() returns minimum element
poll() returns/removes minimum element
remove() removes/returns min element
size() number of elements in queue
41
PriorityQueue: Example
The Map Interface 42

The Map interface maps keys to the


elements. The keys are like indexes. In List,
the indexes are integer. In Map, the keys
can be any objects.

Search keys Corresponding values

Entry


.
.
The Map Interface UML Diagram 43

java.util.Map<K, V>
+clear(): void Removes all mappings from this map.
+containsKey(key: Object): boolean Returns true if this map contains a mapping for the
specified key.
+containsValue(value: Object): boolean Returns true if this map maps one or more keys to the
specified value.
+entrySet(): Set Returns a set consisting of the entries in this map.
+get(key: Object): V Returns the value for the specified key in this map.
+isEmpty(): boolean Returns true if this map contains no mappings.
+keySet(): Set<K> Returns a set consisting of the keys in this map.
+put(key: K, value: V): V Puts a mapping in this map.
+putAll(m: Map): void Adds all the mappings from m to this map.
+remove(key: Object): V Removes the mapping for the specified key.
+size(): int Returns the number of mappings in this map.
+values(): Collection<V> Returns a collection consisting of the values in this map.
Concrete Map Classes 44

«interface»
java.util.Map<K, V>

java.util.AbstractMap<K, V> «interface»


java.util.SortedMap<K, V>
+firstKey(): K
+lastKey(): K
java.util.HashMap<K, V>
+comparator(): Comparator<? super K>)
+HashMap() +headMap(toKey: K): SortedMap
+HashMap(m: Map)
+tailMap(fromKey: K): SortedMap

java.util.LinkedHashMap<K, V>
+LinkedHashMap() java.util.TreeMap<K, V>
+LinkedHashMap(m: Map) +TreeMap()
+LinkedHashMap(initialCapacity: int, +TreeMap(m: Map)
loadFactor: float, accessOrder: boolean) +TreeMap(c: Comparator<? super K>)
HashMap and TreeMap 45

The HashMap and TreeMap classes are


two concrete implementations of the
Map interface. The HashMap class is
efficient for locating a value, inserting a
mapping, and deleting a mapping. The
TreeMap class, implementing SortedMap,
is efficient for traversing the keys in a
sorted order.

HashMap doesn’t maintain any order.


TreeMap sort the entries in ascending
order of keys.
LinkedHashMap maintains the insertion
order.
LinkedHashMap 46

LinkedHashMap was introduced in JDK 1.4. It


extends HashMap with a linked list implementation
that supports an ordering of the entries in the map.
The entries in a HashMap are not ordered, but the
entries in a LinkedHashMap can be retrieved in the
order in which they were inserted into the map
(known as the insertion order), or the order in which
they were last accessed, from least recently
accessed to most recently (access order). The no-arg
constructor constructs a LinkedHashMap with the
insertion order. To construct a LinkedHashMap with
the access order, use the
LinkedHashMap(initialCapacity, loadFactor, true).
47
HashMap: Example 1
48
HashMap
49
HashMap
50
TreeMap: Example
51
LinkedHashMap
52
Resources…

• Liang, Introduction to Java Programming, Eighth Edition, 2011


Pearson Education, Inc. All rights reserved. 0132130807
• http://beginnersbook.com/2013/12/.../
• https://www.javatpoint.com/.../
• https://www.tutorialspoint.com/java/...

You might also like