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

Java Unit 4 Notes

The document provides an overview of the Java Collections Framework, detailing its architecture, interfaces, and classes for managing groups of objects. It covers various collection types such as List, Set, Queue, and their implementations like ArrayList, LinkedList, HashSet, and PriorityQueue, along with their functionalities. Additionally, it explains the characteristics and usage of these collections, emphasizing the importance of maintaining a clean and maintainable codebase.

Uploaded by

Nicky
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)
2 views28 pages

Java Unit 4 Notes

The document provides an overview of the Java Collections Framework, detailing its architecture, interfaces, and classes for managing groups of objects. It covers various collection types such as List, Set, Queue, and their implementations like ArrayList, LinkedList, HashSet, and PriorityQueue, along with their functionalities. Additionally, it explains the characteristics and usage of these collections, emphasizing the importance of maintaining a clean and maintainable codebase.

Uploaded by

Nicky
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/ 28

maintainable codebase.

They enable fine-grained control over which classes can extend or implement a particular
class or interface,
enhancing the security and flexibility of Java applications

CO-IV
Java Collections Framework:
Java Collections Framework: 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.

Lecture-1

Collections in Java
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).

What is Collection in Java


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

What is a framework in Java


o It provides readymade architecture.
o It represents a set of classes and interfaces.
o It is optional.
What is Collection framework

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

Hierarchy of Collection Framework


Let us see the hierarchy of Collection framework. The java.util package contains all
the classes and interfaces for the Collection framework.
Iterable Interface
The Iterable interface is the root interface for all the collection classes. The Collection interface extends
the Iterable interface and therefore all the subclasses of Collection interface also implement the Iterable
interface.

It contains only one abstract method. i.e.,

1. 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. In other words, we can say that the
Collection interface builds the foundation on which the collection framework depends.

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.

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.

To instantiate the List interface, we must use :

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


2. List <data-type> list2 = new LinkedList();
3. List <data-type> list3 = new Vector();
4. List <data-type> list4 = new Stack();

There are various methods in List interface that can be used to insert, delete, and access the elements
from the list.

The classes that implement the List interface are given below.

Lecture-2
The classes that implement the List interface are given below.

ArrayList
The ArrayList class is a resizable array, which can be found in the java.util package. The difference
between a built-in array and an ArrayList in Java, is that the size of an array cannot be modified (if
you want to add or remove elements to/from an array, you have to create a new one).

How the ArrayList works


The ArrayList class has a regular array inside it. When an element is added, it is placed into
the array. If the array is not big enough, a new, larger array is created to replace the old
one and the old one is removed.

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. Consider the following example.

1. import java.util.*;
2. class TestJavaCollection1{
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. //Traversing list through Iterator
10. Iterator itr=list.iterator();
11. while(itr.hasNext()){
12. System.out.println(itr.next());
13. }
14. }
15. }

Output:

Ravi
Vijay
Ravi
Ajay
LinkedList
The LinkedList class is a collection which can contain many objects of the same type, just
like the ArrayList.

The LinkedList class has all of the same methods as the ArrayList class because they both
implement the List interface. This means that you can add items, change items, remove
items and clear the list in the same way.

However, while the ArrayList class and the LinkedList class can be used in the same way,
they are built very differently.

How the LinkedList works


The LinkedList stores its items in "containers." The list has a link to the first container and
each container has a link to the next container in the list. To add an element to the list, the
element is placed into a new container and that container is linked to one of the other
containers in the list.

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.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection2{
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

Vector
The Vector class implements a growable array of objects. Vectors fall in legacy classes, but
now it is fully compatible with collections. It is found in java.util package and implement
the List interface, so we can use all the methods of the List interface as shown below as
follows:

• Vector implements a dynamic array which means it can grow or shrink as required. Like
an array, it contains components that can be accessed using an integer index.
• They are very similar to ArrayList, but Vector is synchronized and has some legacy
methods that the collection framework does not contain.
• It also maintains an insertion order like an ArrayList. Still, it is rarely used in a non-thread
environment as it is synchronized, and due to this, it gives a poor performance in
adding, searching, deleting, and updating its elements.
• The Iterators returned by the Vector class are fail-fast. In the case of concurrent
modification, it fails and throws the ConcurrentModificationException.

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.
Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection3{
3. public static void main(String args[]){
4. Vector<String> v=new Vector<String>();
5. v.add("Ayush");
6. v.add("Amit");
7. v.add("Ashish");
8. v.add("Garima");
9. Iterator<String> itr=v.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }

Output:

Ayush
Amit
Ashish
Garima

Lecture-3
Stack
Java Collection framework provides a Stack class that models and implements a Stack data
structure. The class is based on the basic principle of last-in-first-out. In addition to the basic
push and pop operations, the class provides three more functions of empty, search, and peek.
The class can also be said to extend Vector and treats the class as a stack with the five
mentioned functions. The class can also be referred to as the subclass of Vector.
The below diagram shows the hierarchy of the Stack class:

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.
Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection4{
3. public static void main(String args[]){
4. Stack<String> stack = new Stack<String>();
5. stack.push("Ayush");
6. stack.push("Garvit");
7. stack.push("Amit");
8. stack.push("Ashish");
9. stack.push("Garima");
10. stack.pop();
11. Iterator<String> itr=stack.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Output:

Ayush
Garvit
Amit
Ashish

Queue Interface

The Queue interface is present in java.util package and extends the Collection interface is used to hold
the elements about to be processed in FIFO(First In First Out) order. It is an ordered list of objects with
its use limited to inserting elements at the end of the list and deleting elements from the start of the list,
(i.e.), it follows the FIFO or the First-In-First-Out principle.
Being an interface the queue needs a concrete class for the declaration and the most common classes are
the PriorityQueue and LinkedList in Java. Note that neither of these implementations is thread-
safe. PriorityBlockingQueue is one alternative implementation if the thread-safe implementation is
needed.

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:

1. Queue<String> q1 = new PriorityQueue();


2. Queue<String> q2 = new ArrayDeque();

There are various classes that implement the Queue interface, some of them are given below.

PriorityQueue
A PriorityQueue is used when the objects are supposed to be processed based on the priority. It is known
that a Queue follows the First-In-First-Out algorithm, but sometimes the elements of the queue are
needed to be processed according to the priority, that’s when the PriorityQueue comes into play.
The PriorityQueue is based on the priority heap. The elements of the priority queue are ordered
according to the natural ordering, or by a Comparator provided at queue construction time, depending
on which constructor is used.

In the below priority queue, an element with a maximum ASCII value will have the highest priority.

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.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection5{
3. public static void main(String args[]){
4. PriorityQueue<String> queue=new PriorityQueue<String>();
5. queue.add("Amit Sharma");
6. queue.add("Vijay Raj");
7. queue.add("JaiShankar");
8. queue.add("Raj");
9. System.out.println("head:"+queue.element());
10. System.out.println("head:"+queue.peek());
11. System.out.println("iterating the queue elements:");
12. Iterator itr=queue.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. queue.remove();
17. queue.poll();
18. System.out.println("after removing two elements:");
19. Iterator<String> itr2=queue.iterator();
20. while(itr2.hasNext()){
21. System.out.println(itr2.next());
22. }
23. }
24. }

Output:

head:Amit Sharma
head:Amit Sharma
iterating the queue elements:
Amit Sharma
Raj
JaiShankar
Vijay Raj
after removing two elements:
Raj
Vijay Raj

Deque Interface
The Deque (double-ended queue) interface in Java is a subinterface of the Queue interface
and extends it to provide a double-ended queue, which is a queue that allows elements to
be added and removed from both ends. The Deque interface is part of the Java Collections
Framework and is used to provide a generic and flexible data structure that can be used to
implement a variety of algorithms and data structures.
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:


1. Deque d = new ArrayDeque();

ArrayDeque
The ArrayDeque class in Java is an implementation of the Deque interface that uses a resizable array
to store its elements. This class provides a more efficient alternative to the traditional Stack class,
which was previously used for double-ended operations. The ArrayDeque class provides constant-time
performance for inserting and removing elements from both ends of the queue, making it a good choice
for scenarios where you need to perform many add and remove operations.

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.

ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection6{
3. public static void main(String[] args) {
4. //Creating Deque and adding elements
5. Deque<String> deque = new ArrayDeque<String>();
6. deque.add("Gautam");
7. deque.add("Karan");
8. deque.add("Ajay");
9. //Traversing elements
10. for (String str : deque) {
11. System.out.println(str);
12. }
13. }
14. }

Output:

Gautam
Karan
Ajay
Lecture-4

Set Interface
The set interface is present in java.util package and extends the Collection interface. It is an
unordered collection of objects in which duplicate values cannot be stored. It is an interface
that implements the mathematical set. This interface contains the methods inherited from the
Collection interface and adds a feature that restricts the insertion of the duplicate elements.
There are two interfaces that extend the set implementation

namely SortedSet and NavigableSet.


In the above image, the navigable set extends the sorted set interface. Since a set doesn’t
retain the insertion order, the navigable set interface provides the implementation to navigate
through the Set. The class which implements the navigable set is a TreeSet which is an
implementation of a self-balancing tree. Therefore, this interface provides us with a way to
navigate through this tree.

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.

Set can be instantiated as:

1. Set<data-type> s1 = new HashSet<data-type>();


2. Set<data-type> s2 = new LinkedHashSet<data-type>();
Set<data-type> s3 = new TreeSet<data-type>();
HashSet

Java HashSet class implements the Set interface, backed by a hash table which is actually
a HashMap instance. No guarantee is made as to the iteration order of the hash sets which
means that the class does not guarantee the constant order of elements over time. This class
permits the null element. The class also offers constant time performance for the basic
operations like add, remove, contains, and size assuming the hash function disperses the
elements properly among the buckets, which we shall see further in the article.
Java HashSet Features
A few important features of HashSet are mentioned below:
• Implements Set Interface.
• 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.
• HashSet also implements Serializable and Cloneable interfaces.

Declaration of HashSet

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


Serializable
where E is the type of elements stored in a 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.

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

Output:

Vijay
Ravi
Ajay

LinkedHashSet
The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List
across all elements. When the iteration order is needed to be maintained this class is used.
When iterating through a HashSet the order is unpredictable, while a LinkedHashSet lets us
iterate through the elements in the order in which they were inserted. When cycling through
LinkedHashSet using an iterator, the elements will be returned in the order in which they were
inserted.
The Hierarchy of LinkedHashSet is as follows:

Parameters: The type of elements maintained by this set


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.

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

Output:

Ravi
Vijay
Lecture-5

SortedSet Interface

The SortedSet interface present in java.util package extends the Set interface present in
the collection framework. It is an interface that implements the mathematical set. This
interface contains the methods inherited from the Set interface and adds a feature that
stores all the elements in this interface to be stored in a sorted manner.

Java 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.
Java Map Hierarchy
There are two interfaces for implementing Map in java: Map and SortedMap, and three classes:
HashMap, LinkedHashMap, and TreeMap. The hierarchy of Java Map is given below:

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.

Java HashMap

Java HashMap class implements the Map interface which allows us to store key and value pair, where
keys should be unique. If you try to insert the duplicate key, it will replace the element of the
corresponding key. It is easy to perform operations using the key index like updation, deletion, etc.
HashMap class is found in the java.util package.
HashMap in Java is like the legacy Hashtable class, but it is not synchronized. It allows us to store the
null elements as well, but there should be only one null key. Since Java 5, it is denoted
as HashMap<K,V>, where K stands for key and V for value. It inherits the AbstractMap class and
implements the Map interface.

Points to remember
o Java HashMap contains values based on the key.
o Java HashMap contains only unique keys.
o Java HashMap may have one null key and multiple null values.
o Java HashMap is non synchronized.
o Java HashMap maintains no order.
o The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.

SortedSet is the alternate of Set interface that provides a total ordering on its elements. The elements
of the SortedSet are arranged in the increasing (ascending) order. The SortedSet provides the additional
methods that inhibit the natural ordering of the elements.

The SortedSet can be instantiated as:

1. SortedSet<data-type> set = new TreeSet();

TreeSet
TreeSet is one of the most important implementations of the SortedSet interface in Java that
uses a Tree for storage. The ordering of the elements is maintained by a set using their
natural ordering whether or not an explicit comparator is provided. This must be consistent
with equals if it is to correctly implement the Set interface.

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:

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

Output:

Ajay
Ravi
Vijay

LinkedHashMap in Java
The LinkedHashMap Class is just like HashMap with an additional feature of maintaining an order
of elements inserted into it. HashMap provided the advantage of quick insertion, search, and deletion
but it never maintained the track and order of insertion, which the LinkedHashMap provides where
the elements can be accessed in their insertion order.
Important Features of a LinkedHashMap are listed as follows:
• A LinkedHashMap contains values based on the key. It implements the Map interface and extends
the HashMap class.
• It contains only unique elements.
• It may have one null key and multiple null values.
• It is non-synchronized.
• It is the same as HashMap with an additional feature that it maintains insertion order. For example,
when we run the code with a HashMap, we get a different order of elements.
Declaration:
public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>
Here, K is the key Object type and V is the value Object type
• K – The type of the keys in the map.
• V – The type of values mapped in the map.
It implements Map<K, V> interface, and extends HashMap<K, V> class. Though the Hierarchy of
LinkedHashMap is as depicted in below media as follows:
How LinkedHashMap Work Internally?

A LinkedHashMap is an extension of the HashMap class and it implements the Map interface.
Therefore, the class is declared as:
public class LinkedHashMap
extends HashMap
implements Map
In this class, the data is stored in the form of nodes. The implementation of the LinkedHashMap is
very similar to a doubly-linked list. Therefore, each node of the LinkedHashMap is represented as:

• Hash: All the input keys are converted into a hash which is a shorter form of the key so that the
search and insertion are faster.
• Key: Since this class extends HashMap, the data is stored in the form of a key-value pair.
Therefore, this parameter is the key to the data.
• Value: For every key, there is a value associated with it. This parameter stores the value of the
keys. Due to generics, this value can be of any form.
• Next: Since the LinkedHashMap stores the insertion order, this contains the address to the next
node of the LinkedHashMap.
• Previous: This parameter contains the address to the previous node of the LinkedHashMap.
Lecture-6

Hash table in Java


The Hashtable class implements a hash table, which maps keys to values. Any non-null object can be
used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used
as keys must implement the hashCode method and the equals method.
The java.util.Hashtable class is a class in Java that provides a key-value data structure, similar to the
Map interface. It was part of the original Java Collections framework and was introduced in Java 1.0.
However, the Hashtable class has since been considered obsolete and its use is generally discouraged.
This is because it was designed prior to the introduction of the Collections framework and does not
implement the Map interface, which makes it difficult to use in conjunction with other parts of the
framework. In addition, the Hashtable class is synchronized, which can result in slower performance
compared to other implementations of the Map interface.
In general, it’s recommended to use the Map interface or one of its implementations (such as HashMap
or ConcurrentHashMap) instead of the Hashtable class.
Features of Hashtable
• It is similar to HashMap, but is synchronized.
• Hashtable stores key/value pair in hash table.
• 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.
• The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.
• HashMap doesn’t provide any Enumeration, while Hashtable provides not fail-fast
Enumeration.
The Hierarchy of Hashtable

Sorting in Java
Whenever we do hear sorting algorithms come into play such as selection sort, bubble sort, insertion
sort, radix sort, bucket sort, etc but if we look closer here we are not asked to use any kind of
algorithms. It is as simple sorting with the help of linear and non-linear data structures present within
java. So there is sorting done with the help of brute force in java with the help of loops and there are
two in-built methods to sort in Java.
Ways of sorting in Java
1. Using loops
2. Using sort() method of Arrays class
3. Using sort method of Collections class
4. Sorting on a subarray
Let us discuss all four of them and propose a code for each one of them.
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.

ADVERTISEMENT

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.
Note: String class and Wrapper classes implement the Comparable interface by default. So if you store the
objects of string or wrapper classes in a list, set or map, it will be Comparable by default.

Comparator Interface in Java with Examples



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?
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.
public void sort(List list, ComparatorClass c)
To sort a given List, ComparatorClass must implement a Comparator interface.

How do the sort() method of Collections class work?

Internally the Sort method does call Compare method of the classes it is sorting. To compare
two elements, it asks “Which is greater?” Compare method returns -1, 0, or 1 to say if it is less
than, equal, or greater to the other. It uses this result to then determine if they should be
swapped for their sort.

Properties Class in Java



The Properties class represents a persistent set of properties. The Properties can be saved to a stream
or loaded from a stream. It belongs to java.util package. Properties define the following instance
variable. This variable holds a default property list associated with a Properties object.
Properties defaults: This variable holds a default property list associated with a Properties object.

Features of Properties class:


• Properties is a subclass of Hashtable.
• It is used to maintain a list of values in which the key is a string and the value is also a string i.e; it
can be used to store and retrieve string type data from the properties file.
• Properties class can specify other properties list as it’s the default. If a particular key property is
not present in the original Properties list, the default properties will be searched.
• Properties object does not require external synchronization and Multiple threads can share a
single Properties object.
• Also, it can be used to retrieve the properties of the system.
Advantage of a Properties file
In the event that any data is changed from the properties record, you don’t have to recompile the
java class. It is utilized to store data that is to be changed habitually.
Note: The Properties class does not inherit the concept of a load factor from its superclass, Hashtable.
Declaration
public class Properties extends Hashtable<Object,Object>

Constructors of Properties

1. Properties(): This creates a Properties object that has no default values.


Properties p = new Properties();
2. Properties(Properties propDefault): The second creates an object that uses propDefault for its
default value.
Properties p = new Properties(Properties propDefault);

CO-V
SpringFramework:

You might also like