0% found this document useful (0 votes)
12 views28 pages

Unit Iii Ajava

The document discusses design patterns in software development, categorizing them into creational, structural, and behavioral patterns, each with specific examples and advantages. It also covers the Java Collection Framework, detailing classes like ArrayList and LinkedList, their constructors, and methods. The document emphasizes the importance of design patterns for reusability, system architecture, and simplifying complex interactions in object-oriented systems.

Uploaded by

subashiniapec
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)
12 views28 pages

Unit Iii Ajava

The document discusses design patterns in software development, categorizing them into creational, structural, and behavioral patterns, each with specific examples and advantages. It also covers the Java Collection Framework, detailing classes like ArrayList and LinkedList, their constructors, and methods. The document emphasizes the importance of design patterns for reusability, system architecture, and simplifying complex interactions in object-oriented systems.

Uploaded by

subashiniapec
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

UNIT III

DESIGN PATTERN
A design patterns are well-proved solution for solving the specific problem/task.
A design pattern systematically names, motivates, and explains a general design that addresses a
recurring design problem in object-oriented systems. It describes the problem, the solution, when
to apply the solution, and its consequences. It also gives implementation hints and examples.

Advantage of design pattern:

1. They are reusable in multiple projects.


2. They provide the solutions that help to define the system architecture.
3. They capture the software engineering experiences.
4. They provide transparency to the design of an application.
5. They are well-proved and testified solutions since they have been built upon the
knowledge and experience of expert software developers.

Categorization of design patterns:

Basically, design patterns are categorized into two parts:

1. Core Java (or JSE) Design Patterns.


2. JEE Design Patterns.

Core Java Design Patterns

In core java, there are mainly three types of design patterns, which are further divided into their
sub-parts:

1.Creational Design Pattern

1. Factory Pattern
2. Abstract Factory Pattern
3. Singleton Pattern
4. Prototype Pattern
5. Builder Pattern.

2. Structural Design Pattern

1. Adapter Pattern
2. Bridge Pattern
3. Composite Pattern
4. Decorator Pattern
5. Facade Pattern
6. Flyweight Pattern
7. Proxy Pattern

3. Behavioral Design Pattern

1. Chain Of Responsibility Pattern


2. Command Pattern
3. Interpreter Pattern
4. Iterator Pattern
5. Mediator Pattern
6. Memento Pattern
7. Observer Pattern
8. State Pattern
9. Strategy Pattern
10. Template Pattern
11. Visitor Pattern

Creational design patterns

Creational design patterns are concerned with the way of creating objects. These design
patterns are used when a decision must be made at the time of instantiation of a class But
everyone knows an object is created by using new keyword in java. For example:

StudentRecord s1=new StudentRecord();

Here, we are creating the instance by using the new keyword. Sometimes, the nature of the
object must be changed according to the nature of the program. In such cases, we must get the
help of creational design patterns to provide more general and flexible approach.

Factory Method Pattern

A Factory Pattern or Factory Method Pattern says that just define an interface or abstract class
for creating an object but let the subclasses decide which class to instantiate. In other words,
subclasses are responsible to create the instance of the class.

The Factory Method Pattern is also known as Virtual Constructor.

Advantage of Factory Design Pattern


o Factory Method Pattern allows the sub-classes to choose the type of objects to create.
o It promotes the loose-coupling by eliminating the need to bind application-specific classes
into the code.

Usage of Factory Design Pattern


o When a class doesn't know what sub-classes will be required to create
o When a class wants that its sub-classes specify the objects to be created.
o When the parent classes choose the creation of objects to its sub-classes.

UML for Factory Method Pattern


o We are going to create a Plan abstract class and concrete classes that extends the Plan
abstract class. A factory class GetPlanFactory is defined as a next step.
o GenerateBill class will use GetPlanFactory to get a Plan object. It will pass information
(DOMESTICPLAN / COMMERCIALPLAN / INSTITUTIONALPLAN) to
GetPalnFactory to get the type of object it needs.

Singleton design pattern in Java

Singleton Pattern says that just"define a class that has only one instance and provides a
global point of access to it".

In other words, a class must ensure that only single instance should be created and single object
can be used by all other classes.

There are two forms of singleton design pattern


o Early Instantiation: creation of instance at load time.
o Lazy Instantiation: creation of instance when required.
Advantage of Singleton design pattern
o Saves memory because object is not created at each request. Only single instance is
reused again and again.

Usage of Singleton design pattern


o Singleton pattern is mostly used in multi-threaded and database applications. It is used in
logging, caching, thread pools, configuration settings etc.

Uml of Singleton design pattern

Prototype Design Pattern

Prototype Pattern says that cloning of an existing object instead of creating new one and can
also be customized as per the requirement.

This pattern should be followed, if the cost of creating a new object is expensive and resource
intensive.

Advantage of Prototype Pattern

The main advantages of prototype pattern are as follows:

o It reduces the need of sub-classing.


o It hides complexities of creating objects.
o The clients can get new objects without knowing which type of object it will be.
o It lets you add or remove objects at runtime.

Usage of Prototype Pattern


o When the classes are instantiated at runtime.
o When the cost of creating an object is expensive or complicated.
o When you want to keep the number of classes in an application minimum.
o When the client application needs to be unaware of object creation and representation.

UML for Prototype Pattern

o We are going to create an interface Prototype that contains a


method getClone() of Prototype type.
o Then, we create a concrete class EmployeeRecord which implements Prototype
interface that does the cloning of EmployeeRecord object.
o PrototypeDemo class will uses this concrete class EmployeeRecord.
Structural design patterns

Structural design patterns are concerned with how classes and objects can be composed, to
form larger structures.

The structural design patterns simplifies the structure by identifying the relationships.

These patterns focus on, how the classes inherit from each other and how they are composed
from other classes.

Adapter Pattern

An Adapter Pattern says that just "converts the interface of a class into another interface that
a client wants".

In other words, to provide the interface according to client requirement while using the services
of a class with a different interface.

The Adapter Pattern is also known as Wrapper.

Advantage of Adapter Pattern


o It allows two or more previously incompatible objects to interact.
o It allows reusability of existing functionality.

Usage of Adapter pattern:

It is used:

o When an object needs to utilize an existing class with an incompatible interface.


o When you want to create a reusable class that cooperates with classes which don't
have compatible interfaces.
o When you want to create a reusable class that cooperates with classes which don't
have compatible interfaces.

UML for Adapter Pattern:

There are the following specifications for the adapter pattern:

o Target Interface: This is the desired interface class which will be used by the clients.
o Adapter class: This class is a wrapper class which implements the desired target
interface and modifies the specific request available from the Adaptee class.
o Adaptee class: This is the class which is used by the Adapter class to reuse the existing
functionality and modify them for desired use.
o Client: This class will interact with the Adapter class.

Proxy Pattern

Simply, proxy means an object representing another object.

According to GoF, a Proxy Pattern "provides the control for accessing the original object".

Proxy pattern is also known as Surrogate or Placeholder.

advantage of Proxy Pattern


o It provides the protection to the original object from the outside world.

Usage of Proxy Pattern:

It is used:

o It can be used in Virtual Proxy scenario


o It can be used in Protective Proxy scenario
o It can be used in Remote Proxy scenario
o It can be used in Smart Proxy scenario

Decorator Pattern

A Decorator Pattern says that just "attach a flexible additional responsibilities to an object
dynamically".

In other words, The Decorator Pattern uses composition instead of inheritance to extend the
functionality of an object at runtime.

The Decorator Pattern is also known as Wrapper.

Advantage of Decorator Pattern


o It provides greater flexibility than static inheritance.
o It enhances the extensibility of the object, because changes are made by coding new
classes.
o It simplifies the coding by allowing you to develop a series of functionality from targeted
classes instead of coding all of the behavior into the object.

Usage of Decorator Pattern

It is used:

o When you want to transparently and dynamically add responsibilities to objects without
affecting other objects.
o When you want to add responsibilities to an object that you may want to change in future.
o Extending functionality by sub-classing is no longer practical.

Behavioral Design Patterns

Behavioral design patterns are concerned with the interaction and responsibility of objects.

In these design patterns,the interaction between the objects should be in such a way that they
can easily talk to each other and still should be loosely coupled.

That means the implementation and the client should be loosely coupled in order to avoid hard
coding and dependencies.

Mediator Pattern

A Mediator Pattern says that "to define an object that encapsulates how a set of objects interact".
I will explain the Mediator pattern by considering a problem. When we begin with development,
we have a few classes and these classes interact with each other producing results. Now, consider
slowly, the logic becomes more complex when functionality increases. Then what happens? We
add more classes and they still interact with each other but it gets really difficult to maintain this
code now. So, Mediator pattern takes care of this problem.

Mediator pattern is used to reduce communication complexity between multiple objects or


classes. This pattern provides a mediator class which normally handles all the communications
between different classes and supports easy maintainability of the code by loose coupling.

Benefits:

o It decouples the number of classes.


o It simplifies object protocols.
o It centralizes the control.
o The individual components become simpler and much easier to deal with because they
don't need to pass messages to one another.

The components don't need to contain logic to deal with their intercommunication and
therefore, they are more generic.

Usage:

o It is commonly used in message-based systems likewise chat applications.


o When the set of objects communicate in complex but in well-defined ways.

UML for Mediator Pattern:


Participants:
o ApnaChatroom :- defines the interface for interacting with participants.
o ApnaChatroomImpl :- implements the operations defined by the Chatroom interface.
The operations are managing the interactions between the objects: when one participant
sends a message, the message is sent to the other participants.
o Participant :- defines an interface for the users involved in chatting.
o User1, User2, ...UserN :- implements Participant interface; the participant can be a
number of users involved in chatting. But each Participant will keep only a reference to
the ApnaChatRoom.

Template Pattern

A Template Pattern says that "just define the skeleton of a function in an operation, deferring
some steps to its subclasses".

Benefits:

o It is very common technique for reusing the code.This is only the main benefit of it.
Usage:

o It is used when the common behavior among sub-classes should be moved to a single
common class by avoiding the duplication.

UML for Template Pattern:

COLLECTION FRAMEWORK

The Collection in Java is a framework that provides an architecture to store and manipulate the
group of objects.

Java Collections can achieve all the operations that you perform on a data such as searching,
sorting, insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue,
HashSet, LinkedHashSet, TreeSet).

The Collection framework represents a unified architecture for storing and manipulating a group
of objects. It has:

1. Interfaces and its implementations, i.e., classes


2. Algorithm
Java ArrayList class

Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class
and implements List interface.

The important points about Java ArrayList class are:

o Java ArrayList class can contain duplicate elements.


o Java ArrayList class maintains insertion order.
o Java ArrayList class is non synchronized.
o Java ArrayList allows random access because array works at the index basis.
o In Java ArrayList class, manipulation is slow because a lot of shifting needs to occur if
any element is removed from the array list.
Hierarchy of ArrayList class

As shown in the above diagram, Java ArrayList class extends AbstractList class which
implements List interface. The List interface extends Collection and Iterable interfaces in
hierarchical order.

ArrayList class declaration


public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Clo
neable, Serializable
Constructors of Java ArrayList

Constructor Description

ArrayList() It is used to build an empty array list.

ArrayList(Collecti It is used to build an array list that is initialized with the elements of the collection c.
on<? extends E>
c)
ArrayList(int It is used to build an array list that has the specified initial capacity.
capacity)

Methods of Java ArrayList

Method Description

void add(int index, E element) It is used to insert the specified element at the specified
position in a list.

boolean add(E e) It is used to append the specified element at the end of a list.

booleanaddAll(Collection<?extends It is used to append all of the elements in the specified


E> c)
collection to the end of this list, in the order that they are returned b
the specified collection's iterator.

booleanaddAll(int index, It is used to append all the elements in the specified collection,
Collection<? extends E> c)
starting at the specified position of the list.

void clear() It is used to remove all of the elements from this list.

void It is used to enhance the capacity of an ArrayList instance.


ensureCapacity(intrequiredCapacity)

1. import java.util.*;
2. class ArrayList1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. list.add("Ravi");//Adding object in arraylist
6. list.add("Vijay");
7. list.add("Ravi");
8. list.add("Ajay");
9. //Invoking arraylist object
10. System.out.println(list);
11. } }}
[Ravi, Vijay, Ravi, Ajay]

Java LinkedList class


Java LinkedList class uses a doubly linked list to store the elements. It provides a linked-list data
structure. It inherits the AbstractList class and implements List and Deque interfaces.

The important points about Java LinkedList are:

o Java LinkedList class can contain duplicate elements.


o Java LinkedList class maintains insertion order.
o Java LinkedList class is non synchronized.
o Java LinkedList class can be used as a list, stack or queue.

Hierarchy of LinkedList class


As shown in the above diagram, Java LinkedList class extends AbstractSequentialList class and
implements List and Deque interfaces.

LinkedList class declaration

Let's see the declaration for java.util.LinkedList


class.public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, De
que<E>, Cloneable, Serializable

Constructors of Java LinkedList

Constructor Description

LinkedList() It is used to construct an empty list.

LinkedList(Collection<? extends E> It is used to construct a list containing the


c)
elements of the specified collection, in the order,
they are returned by the collection's iterator.

Methods of Java LinkedList

Method Description

boolean add(E e) It is used to append the specified element to the end of a list.

void add(int index, E element) It is used to insert the specified element at the specified position
index in a list.

void addFirst(E e) It is used to insert the given element at the beginning of a list.
void addLast(E e) It is used to append the given element to the end of a list.

void clear() It is used to remove all the elements from a list.

Object clone() It is used to return a shallow copy of an ArrayList.

boolean contains(Object o) It is used to return true if a list contains a specified element.

Iterator<E>descendingIterator() It is used to return an iterator over the elements in a deque in


reverse sequential order.

E element() It is used to retrieve the first element of a list.

E get(int index) It is used to return the element at the specified position in a list.

E getFirst() It is used to return the first element in a list.

1. import java.util.*;
2. public class LinkedList1{
3. public static void main(String args[]){
4. LinkedList<String> al=new LinkedList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ravi");
8. al.add("Ajay");
9. Iterator<String> itr=al.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }
Output: Ravi
Vijay
Ravi
Ajay

DIFFERENCE BETWEEN ARRAYLIST AND LINKEDLIST

ArrayList and LinkedList both implements List interface and maintains insertion order. Both are
non synchronized classes.However, there are many differences between ArrayList and
LinkedList classes that are given below.

ArrayList LinkedList

1) ArrayList internally uses a dynamic LinkedList internally uses a doubly linked list to
array to store the elements. store the elements.

2) Manipulation with ArrayList is slowbecause Manipulation with LinkedList


it internally uses an array. If any element is is fasterthanArrayList because it uses a doubly
removed from the array, all the bits are shifted linked list, so no bit shifting is required in
in memory. memory.

3) An ArrayList class can act as a list only LinkedList class can act as a list and queue both
because it implements List only. because it implements List and Deque interfaces.

4) ArrayList is better for storing and LinkedList is better for manipulatingdata.


accessingdata.

JAVA HASHSET
Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the
AbstractSet class and implements Set interface.

The important points about Java HashSet class are:


o HashSet stores the elements by using a mechanism called hashing.
o HashSet contains unique elements only.
o HashSet allows null value.
o HashSet class is non synchronized.
o HashSet doesn't maintain the insertion order. Here, elements are inserted on the basis of
their hashcode.
o HashSet is the best approach for search operations.
o The initial default capacity of HashSet is 16, and the load factor is 0.75.

Hierarchy of HashSet class

The HashSet class extends AbstractSet class which implements Set interface. The Set interface
inherits Collection and Iterable interfaces in hierarchical order.

HashSet class declaration

Let's see the declaration for java.util.HashSet class.

public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable

Constructors of Java HashSet class

SN Constructor Description

1) HashSet() It is used to construct a default HashSet.

2) HashSet(int capacity) It is used to initialize the capacity of the hash set to the
given integer value capacity. The capacity grows automatically
as elements are added to the HashSet.

3) HashSet(int capacity, It is used to initialize the capacity of the hash set to the given
float loadFactor)
integer value capacity and the specified load factor.

4) HashSet(Collection<? It is used to initialize the hash set by using the elements of the
extends E> c)
collection c.

Methods of Java HashSet class

SN Modifier Method Description


& Type

1) boolean add(E e) It is used to add the specified element to this


set if it is not already present.

2) void clear() It is used to remove all of the elements from the set.

3) object clone() It is used to return a shallow copy of this HashSet


instance: the elements themselves are not cloned.

4) boolean contains(Object It is used to return true if this set contains the


o)
specified element.

5) boolean isEmpty() It is used to return true if this set contains no elements.

6) Iterator< iterator() It is used to return an iterator over the elements in


E>
this set.

7) boolean remove(Object It is used to remove the specified element from this set if
o)
it is present.
8) int size() It is used to return the number of elements in the set.

9) Spliterato spliterator() It is used to create a late-binding and fail-fast Spliterator


r<E>
over the elements in the set.

import java.util.*;
1. class HashSet1{
2. public static void main(String args[]){
3. //Creating HashSet and adding elements
4. HashSet<String> set=new HashSet();
5. set.add("One");
6. set.add("Two");
7. set.add("Three");
8. set.add("Four");
9. set.add("Five");
10. Iterator<String> i=set.iterator();
11. while(i.hasNext())
12. {
13. System.out.println(i.next());
14. }
15. }
16. }
Five
One
Four
Two
Three

JAVA LINKEDHASHSET CLASS

Java LinkedHashSet class is a Hashtable and Linked list implementation of the set interface. It
inherits HashSet class and implements Set interface.

The important points about Java LinkedHashSet class are:

o Java LinkedHashSet class contains unique elements only like HashSet.


o Java LinkedHashSet class provides all optional set operation and permits null elements.
o Java LinkedHashSet class is non synchronized.
o Java LinkedHashSet class maintains insertion order.

Hierarchy of LinkedHashSet class


The LinkedHashSet class extends HashSet class which implements Set interface. The Set
interface inherits Collection and Iterable interfaces in hierarchical order.

LinkedHashSet class declaration

Let's see the declaration for java.util.LinkedHashSet class.

public class LinkedHashSet<E> extends HashSet<E> implements Set<E>, Cloneable, Serializa


ble
Constructors of Java LinkedHashSet class

Constructor Description

HashSet() It is used to construct a default HashSet.

HashSet(Collection c) It is used to initialize the hash set by using the elements of the collection

LinkedHashSet(int capacity) It is used initialize the capacity of the linked hash set to the
given integer value capacity.

LinkedHashSet(int capacity, It is used to initialize both the capacity and the fill ratio
float fillRatio)
(also called load capacity) of the hash set from its argument.

import java.util.*;
1. class LinkedHashSet1{
2. public static void main(String args[]){
3. //Creating HashSet and adding elements
4. LinkedHashSet<String> set=new LinkedHashSet();
5. set.add("One");
6. set.add("Two");
7. set.add("Three");
8. set.add("Four");
9. set.add("Five");
10. Iterator<String> i=set.iterator();
11. while(i.hasNext())
12. {
13. System.out.println(i.next());
14. }
15. }
16. }
One
Two
Three
Four
Five

JAVA TREESET CLASS

Java TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet
class and implements the NavigableSet interface. The objects of the TreeSet class are stored in
ascending order.

The important points about Java TreeSet class are:

o Java TreeSet class contains unique elements only like HashSet.


o Java TreeSet class access and retrieval times are quiet fast.
o Java TreeSet class doesn't allow null element.
o Java TreeSet class is non synchronized.
o Java TreeSet class maintains ascending order.
Hierarchy of TreeSet class

As shown in the above diagram, Java TreeSet class implements the NavigableSet interface. The
NavigableSet interface extends SortedSet, Set, Collection and Iterable interfaces in hierarchical
order.

TreeSet class declaration

Let's see the declaration for java.util.TreeSet


class.public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneab
le, Serializable

Constructors of Java TreeSet class

Constructor Description

TreeSet() It is used to construct an empty tree set that will be sorted in ascendin
natural order of the tree set.

TreeSet(Collection<? extends E> It is used to build a new tree set that contains the elements of the coll
c)
Methods of Java TreeSet class

Method Description

boolean add(E e) It is used to add the specified element to this set if it is not
already present.

boolean addAll(Collection<? It is used to add all of the elements in the specified


extends E> c)
collection to this set.

E ceiling(E e) It returns the equal or closest greatest element of the


specified element from the set, or null there is no such element.

Iterator descendingIterator() It is used iterate the elements in descending order.

NavigableSet descendingSet() It returns the elements in reverse order.

SortedSet headSet(E toElement) It returns the group of elements that are less than the
specified element.

1. import java.util.*;
2. class TreeSet1{
3. public static void main(String args[]){
4. //Creating and adding elements
5. TreeSet<String> al=new TreeSet<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10. //Traversing elements
11. Iterator<String> itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Output:
Ajay
Ravi
Vijay
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. For example, it may be rollno, name, age or anything else.

compareTo(Object obj) method

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

o positive integer, if the current object is greater than the specified object.
o negative integer, if the current object is less than the specified object.
o zero, if the current object is equal to the specified object.

We can sort the elements of:


1. String objects
2. Wrapper class objects
3. User-defined class objects

Collections class
Collections class provides static methods for sorting the elements of collections. If collection
elements are of Set or Map, we can use TreeSet or TreeMap. However, we cannot sort the
elements of List. Collections class provides methods for sorting the elements of List type
elements.

Method of Collections class for sorting List elements

public void sort(List list): It is used to sort the elements of List. List elements must be of the
Comparable type.

Java Comparable Example

File: Student.java

1. class Student implements Comparable<Student>{


2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10.
11. public int compareTo(Student st){
12. if(age==st.age)
13. return 0;
14. else if(age>st.age)
15. return 1;
16. else
17. return -1;
18. } }

File: TestSort1.java

1. import java.util.*;
2. public class TestSort1{
3. public static void main(String args[]){
4. ArrayList<Student> al=new ArrayList<Student>();
5. al.add(new Student(101,"Vijay",23));
6. al.add(new Student(106,"Ajay",27));
7. al.add(new Student(105,"Jai",21));
8. Collections.sort(al);
9. for(Student st:al){
10. System.out.println(st.rollno+" "+st.name+" "+st.age);
11. } }}
105 Jai 21
101 Vijay 23
106 Ajay 27
JAVA COMPARATOR INTERFACE

Java Comparator interface is used to order the objects of a user-defined class.


This interface is found in java.util package and contains 2 methods compare(Object obj1,Object
obj2) and equals(Object element).
It provides multiple sorting sequences, i.e., you can sort the elements on the basis of any data
member, for example, rollno, name, age or anything else.
Methods of Java Comparator Interface

Method Description

public int compare(Object obj1, It compares the first object with the second object.
Object obj2)
public boolean equals(Object obj) It is used to compare the current object with the specified object.

public boolean equals(Object obj) It is used to compare the current object with the specified object.

Collections class
Collections class provides static methods for sorting the elements of a collection. If collection
elements are of Set or Map, we can use TreeSet or TreeMap. However, we cannot sort the
elements of List. Collections class provides methods for sorting the elements of List type
elements also.
Method of Collections class for sorting List elements

public void sort(List list, Comparator c): is used to sort the elements of List by the given
Comparator.

DIFFERENCE BETWEEN COMPARABLE AND COMPARATOR


Comparable and Comparator both are interfaces and can be used to sort collection
elements.However, there are many differences between Comparable and Comparator interfaces
that are given below.

Comparable Comparator

1) Comparable provides a single sorting The Comparator provides multiple sorting sequences
sequence. In other words, we can sort the
collection on the basis of a single element such In other words, we can sort the collection on the
as id, name, and price. basis of multiple elements such as id, name, and price
etc.

2) Comparable affects the original class, i.e., Comparator doesn't affect the original class, i.e., the
the actual class is modified.
actual class is not modified.

3) Comparable provides compareTo() Comparator provides compare() method to sort


method to sort elements.
elements.

4) Comparable is present in java.lang package. A Comparator is present in the java.util package.

5) We can sort the list elements of Comparable We can sort the list elements of Comparator type
type by Collections.sort(List) method.
by Collections.sort(List, Comparator) method.

You might also like