KEMBAR78
Unit-3 Collections Part 1 | PDF | Class (Computer Programming) | Queue (Abstract Data Type)
0% found this document useful (0 votes)
11 views28 pages

Unit-3 Collections Part 1

The document provides an overview of the Java Collections Framework, which offers a structured way to store and manipulate groups of objects through various interfaces and classes like List, Set, and Map. It discusses legacy classes, their limitations, and modern alternatives introduced in JDK 1.2, emphasizing improved performance and type safety. Additionally, it includes examples of using different collection types such as ArrayList, LinkedList, HashSet, and PriorityQueue.

Uploaded by

v.rithwikaa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views28 pages

Unit-3 Collections Part 1

The document provides an overview of the Java Collections Framework, which offers a structured way to store and manipulate groups of objects through various interfaces and classes like List, Set, and Map. It discusses legacy classes, their limitations, and modern alternatives introduced in JDK 1.2, emphasizing improved performance and type safety. Additionally, it includes examples of using different collection types such as ArrayList, LinkedList, HashSet, and PriorityQueue.

Uploaded by

v.rithwikaa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY

DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE

UNIT – III
Collections : Any group of individual objects that are represented as a single
unit is known as a Java Collection of Objects.

The Collection in Java is a framework that provides an architecture to store


and manipulate the group of objects.

Framework
A framework provides a ready-made structure of classes and interfaces for
building software applications efficiently. It simplifies adding new features by
offering reusable components that perform similar tasks, eliminating the need
to create a framework from scratch for each new project. This approach
enhances object-oriented design, making development quicker, more
consistent, and reliable.

 It provides readymade architecture.


 It represents a set of classes and interfaces.
 It is optional.

Before understanding the different components in the above framework, let’s


first understand a class and an interface.

 Class: A class is a user-defined blueprint or prototype from which


objects are created. It represents the set of properties or methods that
are common to all objects of one type.

 Interface: Like a class, an interface can have methods and variables,


but the methods declared in an interface are by default abstract (only
method signature, nobody). Interfaces specify what a class must do and
not how. It is the blueprint of the class.

The Java Collections Framework (JCF) provides a set of classes and interfaces
to handle different types of collections such as lists, sets, queues, and maps.

Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE

Legacy Classes and Interfaces :


Legacy classes in Java are part of earlier versions of the Java Development Kit
(JDK) that were introduced before the Collections Framework was added in
JDK
1.2. These classes were designed to provide basic data structures and utilities
for handling collections of objects. However, with the introduction of the
Collections Framework, newer, more robust, and flexible classes have largely
replaced these legacy classes in the java.util package.

Here's an overview of the main legacy classes:

1. Vector
 Description: A resizable array that grows dynamically.
 Key Features:
o Synchronized, making it thread-safe.
o Can hold any type of objects, but is less efficient than ArrayList.
 Methods: addElement(), removeElement(), size(), capacity().
 Replacement: ArrayList (unsynchronized version)
or CopyOnWriteArrayList (synchronized version).

2. Stack
 Description: A subclass of Vector implementing the LIFO (Last In, First
Out) stack data structure.
 Key Features:
o Thread-safe but inefficient compared to modern alternatives.
 Methods: push(), pop(), peek(), empty().
 Replacement: Deque (like ArrayDeque) from the Collections Framework.

3. Hashtable
 Description: A dictionary-like collection to store key-value pairs.
 Key Features:
o Synchronized, thread-safe, but less efficient compared to modern
classes.
o Does not allow null keys or values.
 Methods: put(), get(), remove(), containsKey().
 Replacement:
Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE

o HashMap (unsynchronized version).


o ConcurrentHashMap (for thread-safe operations).

4. Enumeration
 Description: An interface used to iterate over elements in
legacy collections like Vector and Hashtable.
 Key Features:
o Limited functionality compared to modern iterators.
 Methods: hasMoreElements(), nextElement().
 Replacement: Iterator and Iterable interface in the Collections
Framework.

Limitations of Legacy Classes:


1. Performance: Legacy classes are synchronized, leading to slower
performance in single-threaded contexts.
2. Type Safety: They do not support generics, so type casting is required,
which can lead to runtime errors.
3. Flexibility: Lack of modern features such as better iteration support.

Modern Replacement / Modern Alternatives :


The Java Collections Framework, introduced in JDK 1.2, provides more robust,
flexible, and type-safe alternatives such as ArrayList, HashMap, HashSet, and
LinkedList. These classes are designed to improve performance, usability, and
scalability.

The Java Collections Framework introduced in JDK 1.2 provides modern,


flexible, and efficient alternatives for handling collections:

 List Interface: ArrayList, LinkedList


 Set Interface: HashSet, TreeSet
 Map Interface: HashMap, TreeMap
 Queue Interface: PriorityQueue, ArrayDeque

By replacing legacy components with their modern counterparts, developers


can take advantage of improved performance, type safety (via generics), and
enhanced functionality.

Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE

Java Collection means a single unit of objects. Java Collection framework


provides many

Interfaces like :

 List
 Set
 Queue
 Deque
 Maps

Classes like :

 ArrayList
 Vector
 LinkedList
 PriorityQueue
 HashSet
 LinkedHashSet
 TreeSet

Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE

1. List An ordered collection (also known as a sequence) that allows


duplicates and provides positional access to elements.

Consider the following example. List<String>


list = new List<>(); list.add("Apple");
list.add("Banana");
list.add("Cherry");

List interface is implemented by the classes

 ArrayList
 LinkedList
 Vector
 Stack

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.

ArrayList <data-type> list1= new ArrayList();

Example Program :

import java.util.*;
class TestJavaCollection1
{
public static void main(String args[])
{
ArrayList<String> list=new ArrayList<String>();
//Creating arraylist
list.add("Grapes");//Adding object in
arraylist list.add("Kiwi");
list.add("Banana");
list.add("Apple");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext())

Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE

{
System.out.println(itr.next());
}
}
}

Output:

Grapes
Kiwi
Banana
Apple

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. It is efficient for insertions
and deletions

List <data-type> list2 = new LinkedList();

import java.util.*;
public class TestJavaCollection2
{
public static void main(String args[])
{
LinkedList<String> al=new LinkedList<>();
al.add("Mango");
al.add("Cherry");
al.add("Apple");
al.add("Grapes");
Iterator<String> itr=al.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Output :
Mango

Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE

Cherry
Apple
Grapes

Vector: Similar to ArrayList but is synchronized, making it slower. It's


considered outdated.

List <data-type> list3 = new Vector();

Example Program :

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

Output:

Ayush
Amit
Ashish
Garima

Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE

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
pop().

List <data-type> list4 = new Stack();

Example Program :

import java.util.*;
public class TestJavaCollection4
{
public static void main(String args[])
{
Stack<String> s = new Stack<String>();
s.push("Ayush");
s.push("Garvit");
s.push("Amit");
s.push("Ashish");
s.push("Garima");
s.pop();
Iterator<String> itr=stack.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}

Output:

Ayush
Garvit
Amit
Ashish

Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE

2. Set : A collection that does not allow duplicates and does not guarantee
any specific order.

Set Interface in Java is present in java.util package. It extends the Collection


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.

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.

Consider the following example.

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
Iterator<String> itr=set.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Output:
Vijay
Ravi
Ajay

Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE

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.

Consider the following example.

import java.util.*;
public class TestJavaCollection8
{
public static void main(String args[])
{
LinkedHashSet<String> set=new LinkedHashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
Iterator<String> itr=set.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}

Output:

Ravi
Vijay
Ajay

Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE

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.

Consider the following example:

import java.util.*;
public class TestJavaCollection9
{
public static void main(String args[])
{
//Creating and adding elements
TreeSet<String> set=new TreeSet<String>();
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());
}
}
}

Output:

Ajay
Ravi
Vijay

3. Queue : In Java, a Queue is a collection designed to hold elements in a


specific order, typically following the First-In-First-Out (FIFO) principle. This
means that the first element added to the queue will be the first one to be
removed.

Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE

The Queue interface is part of the java.util package and provides methods for
adding, removing, and inspecting elements in a queue. The main operations
of a queue are:

1. add(E e): Adds the specified element to the queue. If the queue
cannot accommodate the element, an exception is thrown.
2. offer(E e): Similar to add, but returns false if the queue cannot
accommodate the element (rather than throwing an
exception).
3. remove(): Removes and returns the head of the queue. Throws
an exception if the queue is empty.
4. poll(): Removes and returns the head of the queue, or returns null if
the queue is empty.
5. peek(): Returns the head of the queue without removing it. Returns
null if the queue is empty.
6. element(): Similar to peek, but throws an exception if the queue
is empty.

The Queue interface is implemented by several classes in the Java Collections


Framework. The two most commonly used implementations are :

a) LinkedList
b) PriorityQueue

a) LinkedList

 Implements both the Queue and Deque interfaces.


 Provides methods for adding, removing, and inspecting elements.
 Useful when you need a queue that can grow dynamically.
 Supports both FIFO and LIFO (Last-In-First-Out) operations.

Example Program :

import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {


{
public static void main(String[] args)
{
Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE

Queue<Integer> q = new LinkedList<>();

Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE

// Add elements to the queue


q.add(10);
q.add(20);
q.add(30);

// Peek the head of the queue


System.out.println("Peek: " + q.peek());

// Remove elements from the queue


System.out.println("Removed: " + q.remove());
System.out.println("Removed: " + q.remove());

// Check if the queue is empty


System.out.println("Queue is empty: " + q.isEmpty());
}
}
Output :
Peek: 10
Removed: 10
Removed: 20
Queue is empty: false

b) PriorityQueue
 A priority queue is a type of queue where each element is
associated with a priority.
 The elements are ordered based on their natural ordering or by
a custom comparator.
 Unlike LinkedList, it does not maintain the FIFO order but orders the
elements based on their priority.

Example Program :
import java.util.PriorityQueue;
import java.util.Queue;

public class PriorityQueueExample


{
public static void main(String[] args)

Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE

{
Queue<Integer> queue = new PriorityQueue<>();

// Add elements to the queue


q.add(30);
q.add(10);
q.add(20);

// Elements are dequeued based on priority (natural order)


System.out.println("Removed: " + q.remove()); // 10
System.out.println("Removed: " + q.remove()); // 20
System.out.println("Removed: " + q.remove()); // 30
}
}

4. Deque (Double-Ended Queue) :


A Deque (pronounced "deck") is an interface that extends Queue and allows
elements to be added or removed from both ends (head and tail).
The most common implementation of Deque is LinkedList.
Operations for Deque:
 addFirst(E e)
 offerFirst(E e)
 removeFirst()
 pollFirst()
 addLast(E e)
 offerLast(E e)
 removeLast()
 pollLast()
 getFirst()
 peekFirst()
 getLast()
 peekLast()

Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE

Example Program : import


java.util.Deque; import
java.util.LinkedList;

public class DequeExample


{
public static void main(String[] args)
{
Deque<Integer> d = new LinkedList<>();

// Add elements to the front and back


d.addFirst(10);
d.addLast(20);
d.addFirst(5);

// Remove elements from the front and back


System.out.println("Removed from front: " + d.removeFirst());
System.out.println("Removed from back: " + d.removeLast());

// Peek elements from the front and back


System.out.println("Front element: " + d.peekFirst());
System.out.println("Back element: " + d.peekLast());
}
}
Output :
Removed from front:5
Removed from back :20
Front element :10
Back element:10

5.Maps:
In Java, the Map interface represents a collection of key-value pairs, where each
key is associated with exactly one value. A Map does not extend the
Collection interface, as it stores key-value pairs instead of just elements.

The Map interface is part of the java.util package, and it defines methods to
manipulate key-value pairs such as adding, removing, and retrieving values.

Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE

Key Characteristics of Map:

 Each key in a map is unique.


 A map can have null as a key and/or value, depending on the
implementation (e.g., HashMap allows null keys and values,
while Hashtable does not allow null).
 The map stores data in key-value pairs, with each key mapped to
a specific value.

Methods in the Map Interface:

 put(K key, V value): Associates the specified value with the specified key
in the map. If the map already contains the key, the old value is replaced
by the new value.
 get(Object key): Returns the value to which the specified key is
mapped, or null if the map contains no mapping for the key.
 containsKey(Object key): Returns true if the map contains a mapping
for the specified key.
 containsValue(Object value): Returns true if the map maps one or more
keys to the specified value.
 remove(Object key): Removes the mapping for the specified key
from the map, if present.
 keySet(): Returns a Set view of the keys contained in the map.
 values(): Returns a Collection view of the values contained in the map.
 entrySet(): Returns a Set view of the mappings contained in the
map, where each element is a Map.Entry.
 size(): Returns the number of key-value mappings in the map.
 isEmpty(): Returns true if the map contains no key-value mappings.

Common Implementations of Map:

1. HashMap
o Implements the Map interface and stores key-value pairs using
a hash table.
o It allows null for both keys and values.
o No predictable order: It does not guarantee any specific order
of elements (not sorted).

Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE

2. TreeMap
o Implements the Map interface and stores key-value pairs in
a sorted order.
o It orders the keys according to their natural ordering or by
a specified comparator.
o Does not allow null keys but allows null values.
3. LinkedHashMap
o Extends HashMap and maintains a linked list of entries in
the order they were added.
o Retains the insertion order (or access order if specified),
unlike HashMap.
4. Hashtable
o An older implementation of Map (now mostly replaced
by HashMap).
o Synchronized and does not allow null keys or values.
5. ConcurrentHashMap
o A thread-safe version of HashMap for concurrent use.
o Allows multiple threads to read and write to the map
simultaneously, with better performance compared to
Hashtable.

Example Program :

import java.util.Map; import


java.util.HashMap;

public class MapExample


{
public static void main(String[] args)
{
// Create a HashMap instance
Map<String, Integer> m = new HashMap<>();

// Add elements to the map (key-value pairs)


m.put("Alice", 30);
m.put("Bob", 25);
m.put("Charlie", 35);

// Get value by key

Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE

System.out.println("Bob's age: " + m.get("Bob"));

Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE

// Check if a key exists


System.out.println("Contains key 'Alice'? " + m.containsKey("Alice"));

// Check if a value exists


System.out.println("Contains value 30? " + m.containsValue(30));

// Remove an entry by key


m.remove("Charlie");

// Display all keys and values using keySet() and values()


System.out.println("All keys: " + m.keySet());
System.out.println("All values: " + m.values());

// Size of the map


System.out.println("Size of the map: " + m.size());

// Check if the map is empty


System.out.println("Is map empty? " + m.isEmpty());
}
}
Output :
Bob's age: 25
Contains key 'Alice'? true
Contains value 30? true
All keys: [Alice, Bob]
All values: [30, 25]
Size of the map: 2
Is map empty? false

Points to remember:

 The Map interface provides a structure to store key-value pairs.


 Common implementations like HashMap, TreeMap, and LinkedHashMap
differ in how they store and order the keys.
 The Map interface provides methods to interact with key-value pairs,
such as put(), get(), remove(), containsKey(), and keySet().

………………………………………………………………………………………………………………………

Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE

Iterators : In Java, an Iterator is an object that allows you to traverse through


a collection, such as a List, Set, or Queue, one element at a time. It is part of
the java.util package and is commonly used to iterate over collections in a
consistent and generic way.

The Iterator interface provides a way to access elements from a collection


without exposing the underlying data structure (i.e., it abstracts the details of
the collection). The main advantage of using an iterator is that it works on
various types of collections, making it a flexible and reusable tool.

Core Methods of the Iterator Interface

The Iterator interface defines three primary methods:

1. hasNext():
o Checks if there are more elements in the collection to iterate over.
o Returns true if there is at least one more element,
otherwise returns false.
2. next():
o Returns the next element in the collection.
o Throws NoSuchElementException if no more elements
are available.
3. remove() (optional):
o Removes the last element returned by the iterator from
the collection.
o This method is optional and might throw
UnsupportedOperationException if not supported by
the collection.

Example Program

import java.util.*;
public class IteratorExample {
public static void main(String[] args) {
List<Integer> l = new ArrayList<>();
l.add(10);
l.add(20);
l.add(30);
l.add(40);

Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE

// Getting an iterator for the list


Iterator<Integer> itr = l.iterator();

// Using the iterator to traverse through the list


while (itr.hasNext()) {
Integer element = itr.next();
System.out.println(element);
}
}
}

Output :

10
20
30
40

 if (element > 20)


itr.remove();
System.out.println("Modified List: " + l);

Comparator Interface :
A comparator interface is used to order the objects of user-defined classes. A
comparator object is capable of comparing two objects of the same class.
Following function compare obj1 with obj2.

Syntax:
public int compare(Object obj1, Object obj2);

Suppose we have an Array/ArrayList of our own class type, containing fields


like roll no, name, address, DOB, etc, and we need to sort the array based on
Roll no or name?

Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE

The Comparator interface is essential for custom sorting in Java.


Understanding its proper implementation can help you write cleaner and more
efficient code.

Method 1: One obvious approach is to write our own sort() function using one
of the standard algorithms. This solution requires rewriting the whole sorting
code for different criteria like Roll No. and Name.

Method 2: Using comparator interface- Comparator interface is used to order


the objects of a user-defined class. This interface is present in java.util package
and contains 2 methods compare(Object obj1, Object obj2) and equals(Object
element). Using a comparator, we can sort the elements based on data
members. For instance, it may be on roll no, name, age, or anything else.

Method of Collections class for sorting List elements is used to sort the
elements of List by the given comparator.

Methods in Comparator

1. compare(T o1, T o2)

 Compares two objects and returns:


o Negative value: if o1 is less than o2.
o Zero: if o1 is equal to o2.
o Positive value: if o1 is greater than o2.

2. equals(Object obj)

 Checks if the comparator is equal to another object.

public void sort(List list, ComparatorClass c)

Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE

// Java Program to Demonstrate Working of Comparator Interface


// Importing required classes
import java.io.*;
import java.lang.*;
import java.util.*;
// Class 1
// A class to represent a Student
class Student {
int rollno;
String name, address;

// Constructor
public Student(int rollno, String name, String address)
{
// This keyword refers to current instance itself
this.rollno = rollno;
this.name = name;
this.address = address;
}

// Method of Student class


// To print student details in main()
public String toString()
{
// Returning attributes of Student
return this.rollno + " " + this.name + " "
+ this.address;
}
}

// Class 2
// Helper class implementing Comparator interface
class Sortbyroll implements Comparator<Student> {
// Method
// Sorting in ascending order of roll number
public int compare(Student a, Student b)
{
return a.rollno - b.rollno;
Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE

}
}
// Class 3
// Helper class implementing Comparator interface
class Sortbyname implements Comparator<Student> {
// Method
// Sorting in ascending order of name
public int compare(Student a, Student b)
{
return a.name.compareTo(b.name);
}
}

// Class 4
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an empty ArrayList of Student type
ArrayList<Student> a = new ArrayList<Student>();

// Adding entries in above List


// using add() method
a.add(new Student(111, "Mayank", "london"));
a.add(new Student(131, "Anshul", "nyc"));
a.add(new Student(121, "Solanki", "jaipur"));
a.add(new Student(101, "Aggarwal", "Hongkong"));

// Display message on console for better readability


System.out.println("Unsorted");
// Iterating over entries to print them
for (int i = 0; i < a.size(); i++)
System.out.println(a.get(i));

// Sorting student entries by roll number


Collections.sort(a, new Sortbyroll());

Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE

// Display message on console for better readability System.out.println("\


nSorted by rollno");
// Again iterating over entries to print them
for (int i = 0; i < ar.size(); i++)
System.out.println(a.get(i));

// Sorting student entries by name


Collections.sort(a, new Sortbyname());

// Display message on console for better readability System.out.println("\


nSorted by name");

// // Again iterating over entries to print them


for (int i = 0; i < a.size(); i++)
System.out.println(a.get(i));
}
}
Output :
Unsorteds
111 Mayank london
131 Anshul nyc
121 Solanki jaipur
101 Aggarwal Hongkong

Sorted by rollno
101 Aggarwal Hongkong
111 Mayank london
121 Solanki jaipur
131 Anshul nyc

Sorted by name
101 Aggarwal Hongkong
131 Anshul nyc
111 Mayank london
121 Solanki jaipur

Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE

Random access Interface :


The RandomAccess interface does not have any methods. It's simply a marker
interface (a special kind of interface with no methods) that signifies that an
implementing class supports fast, random access to its elements.

The primary use of the RandomAccess interface is to help optimize algorithms


that access elements randomly by making use of the fact that certain
collections (like ArrayList) can retrieve elements in constant time, while others
(like LinkedList) may take longer (linear time).

It is implemented by classes like ArrayList and Vector that provide constant


time (O(1)) access to elements by index.

Common Implementations of RandomAccess:

 ArrayList
 Vector
 CopyOnWriteArrayList (from java.util.concurrent)

Classes That Do Not Implement RandomAccess:

 LinkedList (Does not implement RandomAccess)


 Stack (It is backed by Vector, but typically not considered to
have random access for typical use cases)

Example Program

import java.util.*;
public class RandomAccessDemo {
public static void main(String[] args) {
List<String> l1 = new ArrayList<>();
List<String> l2 = new LinkedList<>();

// Add elements to the lists


l1.add("Alice");
l1.add("Bob");

l2.add("Charlie");
l2.add("Dave");

// Check if the lists support RandomAccess

Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE

System.out.println("List1 supports RandomAccess: " + (l1 instanceof RandomAccess));


System.out.println("List2 supports RandomAccess: " + (l2 instanceof RandomAccess));
}
}
Output :
List1 supports RandomAccess: true
List2 supports RandomAccess: false

If we are frequently accessing elements by index, we should use collections


that implement RandomAccess (e.g., ArrayList), as this will ensure faster access
compared to collections like LinkedList.
Advantages of the Java Collection Framework

1. Consistent API: The API has a basic set of interfaces like Collection, Set,
List, or Map, all the classes (ArrayList, LinkedList, Vector, etc) that
implement these interfaces have some common set of methods.

2. Reduces programming effort: A programmer doesn’t have to worry


about the design of the Collection but rather he can focus on its best use
in his program. Therefore, the basic concept of Object-oriented
programming (i.e.) abstraction has been successfully implemented.

3. Increases program speed and quality: Increases performance by


providing high-performance implementations of useful data structures
and algorithms because in this case, the programmer need not think of
the best implementation of a specific data structure. He can simply use
the best implementation to drastically boost the performance of his
algorithm/program.

Prepared By,
Ayesha S, Assistant Professor, MJCET

You might also like