Java Collection Framework Overview
Java Collection Framework Overview
Program: [Link]-AIDS
Course Code: BCS-403
Course Name: Object Oriented Programming
with Java
Unit No. 4: JAVA COLLECTION FRAMEWORK
Department of Applied Computational Science & Engg.
Course Code : BCS-403 Course Name: OOP with Java
Course Outcomes :
CO Number Title
CO1 Develop the object-oriented programming concepts using
Java
CO2 Implement exception handling, file handling, and multi-
threading in Java
CO3 Apply new java features to build java programs.
CO4 Analyze java programs with Collection Framework
CO5 Test web and RESTful Web Services with Spring Boot using
Spring Framework concepts
Course Prerequisites:
Syllabus
What is a Framework?
• A framework is a set of classes and interfaces which provide a
ready-made architecture.
• a collection of classes such that all the classes perform the
same kind of task.
Iterable Interface: It is the root interface for the entire collection framework.
The collection interface extends the iterable interface. The Iterable Interface allows
the collection to be iterated over. The collection interface extends the iterable
interface, hence the sub-classes of the collection interface also implement the
iterable interface, i.e., it automatically becomes a part of the iterable interface. It
contains only one abstract method i.e., Iterator<T> iterator()
It returns the iterator over the elements of type T.
Collection Interface
The Collection interface is the interface which is implemented by all the classes in the
collection framework. It declares the methods that every collection will have. Some of
the methods of Collection interface are Boolean add( Object obj), Boolean
addAll(Collection c), void clear(), etc. which are implemented by all the subclasses of
Collection interface.
The following 6 interfaces are described below first later on been discussed with clean
java programs as in implementation.
•Collection interface
•List interface
•Queue interface
•Deque interface (Double-ended queue)
•Set interface
•Map
List Interface
i. List interface is the child interface of Collection interface.
ii. It inhibits a list type data structure in which we can store the ordered
collection of objects.
iii. It can have duplicate values.
iv. List interface is implemented by the classes ArrayList, LinkedList,
Vector, and Stack.
v. To instantiate the List interface, we must use :
There are various methods in List interface that can be used to insert,
delete, and access the elements from the list.
ArrayList
[Link] [Link].*;
[Link] TestJavaCollection{
[Link] static void main(String args[]){
[Link]<String> list=new ArrayList<String>();//
Creating arraylist
[Link] is class which implements List interface (create and Array)
and Itrable Interface (traversal – working with index of the array)
[Link]("Ravi");//Adding object in arraylist list[0]=“Ravi”
[Link]("Vijay"); list[1] = “Vijay”
[Link]("Ravi"); list[2] = “Ravi”
[Link]("Ajay"); list[3] = “Ajay” OUTPUT: Ravi
10.//Traversing list through Iterator Vijay
[Link] itr=[Link](); Ravi
[Link]([Link]()){ Ajay
[Link]([Link]());
14.}
15.}
16.}
Program Name: [Link]-AIDS Program Code: 163
Department of Applied Computational Science & Engg.
Course Code : BCS-403 Course Name: OOP with Java
import [Link].*;
//creating an ArrayList
ArrayList<String> str= new ArrayList<String>();
//add elements
[Link]("Hello");
[Link]("Hi");
[Link]("Namaste");
[Link]("Bonjour");
LinkedList
i. LinkedList implements the Collection interface.
ii. LinkedList uses Doubly Linked List to store its elements
while ArrayList internally uses a dynamic array to store its
elements.
iii. LinkedList is faster in the manipulation of data as it is
node-based which makes it unique.
iv. LinkedList is non-synchronized means multiple threads at a
time can access the code. This means if one thread is
working on LinkedList, other threads can also get a hold of it.
Multiple operations on LinkedList can be performed at a
time. For example, if addition is being performed by one
thread, other operation can be performed by some other
thread too.
v. It can store the duplicate elements.
Vector
i. Like ArrayList, Vectors in Java are used for dynamic arrays.
iii. Vector is synchronised. Synchronised means only one thread at a time can
access the code. This means if one thread is working on Vector, no other
thread can get a hold of it. Only one operation on vector can be
performed at a time. For example, if addition is being performed by one
thread, other operation cannot be performed until the first one is over.
import [Link].*;
public class ExampleVector{
public static void main(String args[]){
//creating a Vector
Vector<Integer> v= new Vector<Integer>();
//add elements
[Link](19);
[Link](88);
[Link](1);
[Link](39);
//displaying the Vector
[Link](v); 19, 88, 1, 39
Stack
i. Stack class extends the Vector class and it is its subclass.
ii. It works on the principle of Last-In, First-Out.
iii. In order to put an object on the top of the stack, we call
the push() method.
iv. To remove and return the top element in the stack, we
call pop() method.
v. There are other methods like peek(), search() and
empty() which are used to perform operations on the stack.
vi. One thing to note is that Stack is thread-safe. It might be
overhead in an environment where the thread-safety concept is
not needed. So, ArrayDeque is preferred.
import [Link].*;
public class StackExample{
public static void main(String args[]){
//creating a Stack
Stack<Integer> s= new Stack<Integer>();
//the size remains the same as peek does not remove the element
[Link]("Size after Peek "+[Link]());
}
}
QUEUE
Department of Applied Computational Science & Engg.
Course Code : BCS-403 Course Name: OOP with Java
Queue Interface
i. The Queue Interface extends the Collection interface.
ii. ii. It uses the principle of First-In, First-Out (FIFO).
iii. A Queue is an ordered list where there is a need to maintain the order of the
elements.
iv. It has classes like PriorityQueue and ArrayDeque.
v. The most famous implementation is that of PriorityQueue.
PriorityQueue
i. The PriorityQueue class extends AbstractQueue and implements the Queue
Interface.
ii. As the name suggests, they follow the principle of priority of the elements.
iii. We know that we follow First-In, First-Out for queues, but at times, the elements
need to be processed in terms of their priority. This is where the PriorityQueue
comes into play.
iv. It does not allow null values to be stored inside it.
v. The add() method is used to add an element while the poll() method is used to
remove the top-most element. While, peek() is used to display the top-most
element.
import [Link].*;
public class ScalerTopics{
public static void main(String args[])
{
// Creating a priority queue
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
//displaying the initial size
[Link]("Size at the beginning "+[Link]());
// Adding elements using add()
[Link](9);
[Link](29);
[Link](19);
[Link](7);
//displaying the PriorityQueue
[Link]("New PriorityQueue" + pq);
Deque Interface
i. Deque interface extends the Queue interface.
ii. In Deque, we can remove and add the elements from both
the side.
iii. Deque stands for a double-ended queue which enables us
to perform the operations at both the ends.
iv. Deque can be instantiated as:
Deque d = new ArrayDeque();
ArrayDeque
• ArrayDeque class implements the Deque interface. It facilitates us to use the Deque.
• Unlike queue, we can add or delete the elements from both the ends.
[Link] [Link].*;
[Link] class TestJavaCollection6{
[Link] static void main(String[] args) {
4.//Creating Deque and adding elements
OUTPUT: Gautam
[Link]<String> deque = new ArrayDeque<String>();
Karan
Ajay
[Link]("Gautam");
[Link]("Karan");
[Link]("Ajay");
9.//Traversing elements
[Link] (String str : deque) {
[Link](str);
12.}
13.}
14.}
Set Interface
i. The Set interface defines an unordered collection.
ii. Set Interface in Java is present in [Link] package.
iii. It extends the Collection Interface.
iv. It cannot store duplicate values in this.
v. It can store at most one null value in Set.
vi. The Set Interface is implemented by popular classes like HashedSet,
LinkedHashSet, and TreeSet.
vii. Set can be instantiated as:
Set<data-type> s1 = new HashSet<data-type>();
Set<data-type> s2 = new LinkedHashSet<data-
type>();
Set<data-type> s3 = new TreeSet<data-type>();
Set Interface
[Link] [Link].*;
[Link] class setExample{
3. public static void main(String[] args)
4. {
5. // creating LinkedHashSet using the Set
6. Set<String> data = new LinkedHashSet<String>();
7.
8. [Link](“CSDS1");
9. [Link](“CSDS2");
10. [Link](“CSDS3");
11. [Link](“CSDS4");
12.
13. [Link](data);
14. }
15.}
On the Set, we can perform all the basic mathematical operations like
intersection, union and difference.
Suppose, we have two sets, i.e., set1 = [22, 45, 33, 66, 55, 34, 77] and set2 =
[33, 2, 83, 45, 3, 12, 55]. The following operation can be performed on the Set:
•Intersection: The intersection operation returns all those elements which are present in both the
set. The intersection of set1 and set2 will be [33, 45, 55].
•Union: The union operation returns all the elements of set1 and set2 in a single set, and that set
can either be set1 or set2. The union of set1 and set2 will be [2, 3, 12, 22, 33, 34, 45, 55, 66, 77,
83].
•Difference: The difference operation deletes the values from the set which are present in another
set. The difference of the set1 and set2 will be [66, 34, 22, 77].
•Set1 – set2 = set2 – set1
•[22, 66, 34, 77] != [2, 83, 3, 12]
•In set, addAll() method is used to perform the union, retainAll() method is used to perform the
intersection , removeAll() method is used to perform difference.
Output:
Union of set1 and set2 is:[33, 66, 34, 2, 83, 3, 22,
55, 12, 45, 77]
Intersection of set1 and set2 is:[33, 55, 45]
Difference of set1 and set2 is:[66, 34, 22, 77]
boolean add(E e)Adds the specified element to this set if it is not already present (optional
operation).
boolean addAll(Collection<? extends E> c)Adds all of the elements in the specified collection to
this set if they're not already present (optional operation).
void clear()Removes all of the elements from this set (optional operation).
boolean contains(Object o)Returns true if this set contains the specified element.
boolean containsAll(Collection<?> c)Returns true if this set contains all of the elements of the
specified collection.
boolean equals(Object o)Compares the specified object with this set for equality.
int hashCode()Returns the hash code value for this set.
boolean isEmpty()Returns true if this set contains no elements.
Iterator<E> iterator()Returns an iterator over the elements in this set.
boolean remove(Object o)Removes the specified element from this set if it is present
(optional operation).
boolean removeAll(Collection<?> c)Removes from this set all of its elements that are
contained in the specified collection (optional operation).
boolean retainAll(Collection<?> c)Retains only the elements in this set that are contained in
the specified collection (optional operation).
int size()Returns the number of elements in this set (its cardinality).
default Spliterator<E> spliterator()Creates a Spliterator over the elements in this set.
Object[] toArray()Returns an array containing all of the elements in this set.
<T> T[] toArray(T[] a)Returns an array containing all of the elements in this set; the
runtime type of the returned array is that of the specified array.
HashSet
•Java HashSet class implements the Set interface, backed by a hash table
which is actually a HashMap instance.
•The underlying data structure for HashSet is Hashtable.
•As it implements the Set Interface, duplicate values are not allowed.
•Objects that you insert in HashSet are not guaranteed to be inserted in the same order. Objects
are inserted based on their hash code.
•NULL elements are allowed in HashSet.
.
LinkedHashSet
TreeSet
HashSet Interface
HashSet Interface
Recommended Books
Text books: Java The Complete Reference
“Java Black Book”