0% found this document useful (0 votes)
8 views41 pages

Unit 4 - Collection Framework

The document provides an overview of the Collection Framework in Java, detailing various interfaces such as Collection, List, Set, and Map, along with their implementations like ArrayList, HashSet, and HashMap. It explains key concepts including iterators, sorting with Comparable and Comparator interfaces, and the differences between HashMap and Hashtable. Additionally, it covers the properties and use cases of different collection types, emphasizing their functionalities and performance characteristics.

Uploaded by

rajatmaurya7906
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)
8 views41 pages

Unit 4 - Collection Framework

The document provides an overview of the Collection Framework in Java, detailing various interfaces such as Collection, List, Set, and Map, along with their implementations like ArrayList, HashSet, and HashMap. It explains key concepts including iterators, sorting with Comparable and Comparator interfaces, and the differences between HashMap and Hashtable. Additionally, it covers the properties and use cases of different collection types, emphasizing their functionalities and performance characteristics.

Uploaded by

rajatmaurya7906
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/ 41

KIET Group of Institutions (College Code: 029)

Object Oriented Programming with Java


Unit 4
Collection Framework

1
 Collection in Java,
 Collection Framework in Java,
 Hierarchy of Collection Framework,
 Iterator Interface,
 Collection Interface,
 List Interface, ArrayList, LinkedList, Vector, Stack, Queue Interface,
 Set Interface, HashSet, LinkedHashSet,
 SortedSet Interface, TreeSet,
 Map Interface, HashMap Class,
 LinkedHashMap Class,
 TreeMap Class,
 Hashtable Class, Sorting,
 Comparable Interface, Comparator Interface,
 Properties Class in Java.
Collection Interface

• A Collection represents a single unit of objects, i.e., a group.

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


List Interface

• List interface is the child interface of Collection interface. It


inhibits a list type data structure in which we can store the
ordered collection of objects. It can have duplicate values.
• List interface is implemented by the classes:
 ArrayList
 LinkedList
 Vector and
 Stack
List <data-type> list1= new ArrayList();
List <data-type> list2 = new LinkedList();
List <data-type> list3 = new Vector();
List <data-type> list4 = new Stack();

List interface that can be used to


• insert,
• delete, and
• access the elements from the list.
Iterator
• Iterators in Java are used in the Collection framework to retrieve
elements one by one. It is a universal iterator as we can apply it to
any Collection object. By using Iterator, we can perform both read
and remove operations. An iterator object can be created by calling
the iterator() method present in the Collection interface.
Iterator itr = c.iterator();
1. hasNext(): Returns true if the iteration has more elements.
2. 2. next(): Returns the next element in the iteration. It
throws NoSuchElementException if no more element is present.
public Object next();
3. remove(): Removes the next element in the iteration. This method
can be called only once per call to next().
public void remove();
ArrayList

• The ArrayList class implements the List interface. It uses


a dynamic array to store the duplicate element of different
data types.
• The ArrayList class maintains the insertion order and is
non-synchronized.
• The elements stored in the ArrayList class can be
randomly accessed.
import java.util.*;
class TestJavaCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>(); //Creating arraylist
list.add("Ravi"); //Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
LinkedList

• LinkedList implements the Collection interface.


• It uses a doubly linked list internally to store the elements. It
can store the duplicate elements.
• It maintains the insertion order and is not synchronized. In
LinkedList, the manipulation is fast because no shifting is
required.
import java.util.*;
public class TestJavaCollection2{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Vector

• Vector uses a dynamic array to store the data elements. It is


similar to ArrayList. However,
• It is synchronized and contains many methods that are not the
part of Collection framework.
import java.util.*;
public class TestJavaCollection3{
public static void main(String args[]){
Vector<String> v=new Vector<String>();
v.add("Ayush");
v.add("Amit");
v.add("Ashish");
v.add("Garima");
Iterator<String> itr=v.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Stack

The stack is the subclass of Vector. It implements the last-in-first-


out data structure, i.e., Stack.
The stack contains all of the methods of Vector class and also
provides its methods like
 boolean push()
 boolean peek()
 boolean push(object o)
which defines its properties
import java.util.*;
public class TestJavaCollection4{
public static void main(String args[]){
Stack<String> stack = new Stack<String>();
stack.push("Ayush");
stack.push("Garvit");
stack.push("Amit");
stack.push("Ashish");
stack.push("Garima");
stack.pop();
Iterator<String> itr=stack.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Queue Interface

Queue interface maintains the first-in-first-out order. It can


be defined as an ordered list that is used to hold the
elements which are about to be processed. There are
various classes like PriorityQueue, Deque, and
ArrayDeque which implements the Queue interface.
Queue interface can be instantiated as:

Queue<String> q1 = new PriorityQueue();


Queue<String> q2 = new ArrayDeque();
PriorityQueue

• The PriorityQueue class implements the Queue interface. It holds


the elements or objects which are to be processed by their priorities.
• PriorityQueue doesn't allow null values to be stored in the queue.
• queue.element(): Retrieves, but does not remove, the head of this queue.
Throws an exception if the queue is empty.
• queue.peek(): Retrieves, but does not remove, the head of this queue, or
returns null if the queue is empty.
• Both methods are used to demonstrate that they return the same result,
the head of the queue.
• queue.remove(): Removes a single instance of the specified element from
this queue, if it is present. Throws an exception if the queue is
empty.queue.
• poll(): Retrieves and removes the head of this queue, or returns null if the
queue is empty. Both methods are used to remove two elements from the
queue.
import java.util.*;
public class TestJavaCollection5{
public static void main(String args[]){
PriorityQueue<String> queue=new PriorityQueue<String>();
queue.add("Amit Sharma");
queue.add("Vijay Raj");
queue.add("JaiShankar");
queue.add("Raj");
System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
System.out.println("iterating the queue elements:");
Iterator itr=queue.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
queue.remove();
queue. poll();
System.out.println("after removing two elements:");
Iterator<String> itr2=queue.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
}
Deque Interface

• Deque interface extends the Queue interface. In Deque,


we can remove and add the elements from both the
side.
• Deque stands for a double-ended queue which enables us
to perform the operations at both the ends.
• Deque can be instantiated as:
• Deque d = new ArrayDeque();
Set Interface

It represents the unordered set of elements which doesn't allow us to


store the duplicate items. We can store at most one null value in
Set. Set is implemented by
 HashSet
 LinkedHashSet, and
 TreeSet

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

HashSet class implements Set Interface.


It represents the collection that uses a hash table for
storage.
Hashing is used to store the elements in the HashSet.
It contains unique items.
• HashSet does not maintain insertion order, the
output order might be different each time.
• Application of HashSet: Where unique entries are
required like storting Email id, Student Roll No., Cache
History of URL,
import java.util.*;
public class TestJavaCollection7{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements Output:
Iterator<String> itr=set.iterator(); Vijay
while(itr.hasNext()){
System.out.println(itr.next()); Ravi
} Ajay
}
}
LinkedHashSet

• LinkedHashSet class represents the LinkedList


implementation of Set Interface.
• It extends the HashSet class and implements Set interface.
• Like HashSet, It also contains unique elements. It
maintains the insertion order and permits null
elements.
TreeSet

• Java TreeSet class implements the Set interface that uses


a tree for storage.
• Like HashSet, TreeSet also contains unique elements.
However, the access and retrieval time of TreeSet is quite
fast.
• The elements in TreeSet stored in ascending order.

Output:
Ajay
import java.util.*;
public class TestJavaCollection9{
public static void main(String args[]){
Ravi
//Creating and adding elements
TreeSet<String> set=new TreeSet<String>();
Vijay
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Map Interface
• A map contains values on the basis of key, i.e. key and
value pair. Each key and value pair is known as an
entry. A Map contains unique keys.

• A Map is useful if you have to search, update or delete


elements on the basis of a key.
Map Hierarchy

A Map doesn't allow duplicate keys, but you can have duplicate values.
HashMap and LinkedHashMap allow null keys and values, but TreeMap
doesn't allow any null key or value.
General Properties of Map
• Key-Value Pairs:
– A Map stores data in key-value pairs. Each key is
associated with exactly one value.
• Unique Keys:
– Keys in a Map are unique. If you try to insert a duplicate
key, the old value associated with that key will be replaced
by the new value.
• Null Values and Keys:
– HashMap allows one null key and multiple null values.
– TreeMap does not allow null keys as it needs to sort the
keys, but it allows multiple null values.
– LinkedHashMap allows one null key and multiple null
values.
Order:
• HashMap does not guarantee any specific order of the keys.
• LinkedHashMap maintains the insertion order of keys.
• TreeMap maintains keys in a sorted order according to their
natural ordering or a specified comparator.
Performance:
• HashMap provides O(1) time complexity for put, get,
and remove operations on average.
• TreeMap provides O(log n) time complexity for put,
get, and remove operations as it is based on a
Red-Black tree.
• LinkedHashMap provides O(1) time complexity for
put, get, and remove operations, similar to
HashMap, but with a slightly higher overhead due
to maintaining the insertion order.
Concurrency:
• HashMap and TreeMap are not synchronized and are
not thread-safe.
HashMap
Example: An application that frequently needs to cache data for quick access.
Reason: HashMap provides average O(1) time complexity for get and put operations,
making it ideal for caching scenarios where quick access to data is critical.
TreeMap
Use Case: Storing Sorted Data
Example: An application that needs to maintain a directory of employees sorted by
their employee IDs.
Reason: TreeMap maintains the keys in a sorted order, making it suitable for scenarios
where sorted data retrieval is required.
LinkedHashMap
Use Case: Maintaining Insertion Order
Example: An application that needs to maintain the order of user actions for session
tracking.
Reason: LinkedHashMap maintains the insertion order, which is useful for preserving
the sequence of actions or events.
HashTable
Features of Hashtable
1. It is similar to HashMap, but is synchronized.
2. The initial default capacity of Hashtable class is 11.
3. Hashtable stores key/value pair in hash table.
4. In Hashtable we specify an object that is used as a key, and the value we
want to associate to that key. The key is then hashed, and the resulting
hash code is used as the index at which the value is stored within the table
5. Load factor =.75 (it is used at the time of resizing). The Hashtable has a
default load factor of 0.75.
6. When the number of entries exceeds 75% of the capacity, the Hashtable
rehashes and doubles its capacity plus one. This means if the capacity is
C, after rehashing, the new capacity will be
2*C + 1.
1. HashTable output is Top to Bottom and Right to left.
Differences between HashMap and HashTable

Characterstics Hash Map HashTable


Null key Unique (Single) Not allowed
Null Value Multiple No null value
Order No insertion order is From top to bottom and
maintained right to left
Default Size 16 11
LoadFactor .75 .75

Synchronization Not Synchronized Synchronized


Use Single Threaded Multithreaded
Environment Environment
Java Comparable interface
Java Comparable interface is used to order the objects of the user-defined
class. This interface is found in java.lang package and contains only one
method named compareTo(Object).
It provides a single sorting sequence only, i.e., you can sort the elements on the
basis of single data member only.
compareTo(Object obj) method

public int compareTo(Object obj): It is used to compare the current object


with the specified object. It returns
 positive integer, if the current object is greater than the specified object.
 negative integer, if the current object is less than the specified object.
 zero, if the current object is equal to the specified object.
We can sort the elements of:
String objects
Wrapper class objects
User-defined class objects
Comparator Interface

• The Comparator interface in Java is used to define a custom ordering for


objects.
• Unlike the Comparable interface, which defines a natural ordering
within the objects of a class, the Comparator interface allows you to
define multiple ways to compare objects , which can be useful when you
want to sort objects based on different criteria without modifying the
class itself.
Comparator Interface Methods
• compare Method: This method compares two objects.
int compare(T o1, T o2);
 Returns a negative integer if o1 is less than o2.
 Returns zero if o1 is equal to o2.
 Returns a positive integer if o1 is greater than o2.
Thanks

You might also like