Unit 1 Class Notes
Unit 1 Class Notes
▪1
UNIT – I
COLLECTIONS FRAMEWORK AND UTILITY CLASSES
Reinforcement Learning 2
Introduction to Collections Framework
Reinforcement Learning 3
Introduction to Collections Framework
Reinforcement Learning 4
Introduction to Collections Framework
Reinforcement Learning 5
Value Prediction with function Approximation
Difficulties:
In many tasks to which we would like to apply
reinforcement learning, most states encountered will
never have been experienced exactly before.
This will almost always be the case when the state or
action spaces include continuous variables or
complex sensations, such as a visual image.
Solution – generalize from previously experienced
states to the ones that have never been seen.
Reinforcement Learning 6
Collections Interface
Why collections?
3 public boolean remove(Object element) It is used to delete an element from the collection.
13
Iterable and Iterator Interface
Iterable Interface in Java
❑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.,
Iterator<T> iterator()
It returns the iterator over the elements of type T.
15
Iterator Interface
❑Iterator Interface:
❑Iterator is an object that enables you to traverse through a collection.
❑Can be used to remove elements from the collection selectively, if desired.
❑There are only three methods in the Iterator interface.
❑They are:
List Interface
❑List interface extends from Collection interface
❑It stores elements in a sequential manner
❑Elements in the list can be accessed or inserted based on their
position
❑Starts with zero based index
❑Can contain duplicate elements
❑An Iterator can be used to access the elements of the List
❑To instantiate the List interface, we must use :
❑List <data-type> list1= new ArrayList();
❑List <data-type> list2 = new LinkedList();
❑List <data-type> list3 = new Vector();
❑List <data-type> list4 = new Stack();
18
List Interface
19
ArrayList
ArrayList
ArrayList:
❑The ArrayList class implements the List interface.
❑It uses a dynamic array to store the duplicate element of
different data types.
❑It is like an array, but there is no size limit. We can add or
remove elements anytime.
❑The ArrayList class maintains the insertion order.
❑The elements stored in the ArrayList class can be randomly
accessed because it works on an index basis.
21
ArrayList
ArrayList:
❑In ArrayList, manipulation is a little bit slower than the
LinkedList in Java because a lot of shifting needs to occur if
any element is removed from the array list.
❑We can not create an array list of the primitive types, such as
int, float, char, etc. It is required to use the required wrapper
class in such cases. For example:
❑ArrayList<int> al = ArrayList<int>(); // Not Valid
❑ArrayList<Integer> al = new ArrayList<Integer>(); // Valid
22
ArrayList
Constructors of ArrayList
Constructor Description
1.ArrayList() It is used to build an empty
array list.
23
ArrayList : Program 1
import java.util.*;
class TestJavaCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Roopa");//Adding object in arraylist
list.add(“Amudha");
list.add("Raji");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} }}
24
Methods of ArrayList
Method Description
boolean addAll(int index, It is used to append all the elements in the specified
Collection<? extends E> c) collection, starting at the specified position of the list.
void clear() It is used to remove all of the elements from this list.
It is used to fetch the element from the particular position of
E get(int index)
the list.
boolean isEmpty() It returns true if the list is empty, otherwise false.
It is used to return the index in this list of the last occurrence
int lastIndexOf(Object o) of the specified element, or -1 if the list does not contain this
element.
It is used to return an array containing all of the elements in
Object[] toArray()
this list in the correct order.
25
Methods of ArrayList
Method Description
It returns true if the list contains the specified
boolean contains(Object o)
element.
It is used to return the index in this list of the first
int indexOf(Object o) occurrence of the specified element, or -1 if the List
does not contain this element.
It is used to remove the element present at the
E remove(int index)
specified position in the list.
It is used to remove the first occurrence of the
boolean remove(Object o)
specified element.
boolean removeAll(Collection<?> c) It is used to remove all the elements from the list.
boolean removeIf(Predicate<? super It is used to remove all the elements from the list
E> filter) that satisfies the given predicate.
protected void removeRange(int It is used to remove all the elements lies within the
fromIndex, int toIndex) given range.
void replaceAll(UnaryOperator<E> It is used to replace all the elements from the list
operator) with the specified element.
It is used to replace the specified element in the list,
E set(int index, E element) 26
present at the specified position.
Methods of ArrayList
Method Description
void sort(Comparator<? It is used to sort the elements of the list on the basis of the
super E> c) specified comparator.
List<E> subList(int It is used to fetch all the elements that lies within the
fromIndex, int toIndex) given range.
It is used to return the number of elements present in the
int size()
list.
It is used to trim the capacity of this ArrayList instance to
void trimToSize()
be the list's current size.
27
Java ArrayList Example Programs
30
Java ArrayList Example Programs
Program8
import java.util.*;
class ArrayList8 {
34
Java ArrayList example to remove elements
Example Programs
Output:
An initial list of elements: [Ravi, Vijay, Ajay, Anuj, Gaurav]
After invoking remove(object) method: [Ravi, Ajay, Anuj, Gaurav]
After invoking remove(index) method: [Ajay, Anuj, Gaurav]
Updated list : [Ajay, Anuj, Gaurav, Ravi, Hanumat]
After invoking removeAll() method: [Ajay, Anuj, Gaurav]
After invoking removeIf() method: [Anuj, Gaurav]
After invoking clear() method: []
35
Iterating Collection Example Programs
import java.util.*;
class ArrayList4{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
38
Java ArrayList example of isEmpty() method
Example Programs
import java.util.*;
class ArrayList10{
39
LinkedList
LinkedList
LinkedList:
❑Java LinkedList class uses a doubly linked list to store the
elements.
❑It provides a linked-list data structure.
❑It inherits the Abstract List class and implements List and
Deque interfaces.
❑Java LinkedList class can contain duplicate elements.
❑Java LinkedList class maintains insertion order.
❑Java LinkedList class is non synchronized.
❑In Java LinkedList class, manipulation is fast because no
shifting needs to occur.
❑Java LinkedList class can be used as a list, stack or queue.
41
Constructors of LinkedList
42
Methods of 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 It is used to insert the specified element at the specified position
element) index in a list.
boolean addAll(Collection<? It is used to append all of the elements in the specified collection
extends E> c) to the end of this list, in the order that they are returned by the
specified collection's iterator.
boolean addAll(Collection<? It is used to append all of the elements in the specified collection
extends E> c) to the end of this list, in the order that they are returned by the
specified collection's iterator.
boolean addAll(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 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.
43
Methods of LinkedList
Method Description
Iterator<E> It is used to return an iterator over the elements in a deque in
descendingIterator() 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.
Output:
[Volvo, BMW, Ford, Mazda]
47
Java LinkedList Example Programs
import java.util.*;
public class LinkedList1{
public static void main(String args[]){
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
} Output:
} Ravi
Vijay
Ravi
Ajay
48
Java LinkedList to add Elements Example Programs
import java.util.*;
public class LinkedList2{
public static void main(String args[]){
LinkedList<String> ll=new LinkedList<String>();
System.out.println("Initial list of elements: "+ll);
ll.add("Ravi");
ll.add("Vijay");
ll.add("Ajay");
System.out.println("After invoking add(E e) method: "+ll);
//Adding an element at the specific position
ll.add(1, "Gaurav");
System.out.println("After invoking add(int index, E element)
method: "+ll);
49
Java LinkedList to add Elements Example Programs
50
Java LinkedList to add Elements Example Programs
} Output:
Initial list of elements: []
After invoking add(E e) method: [Ravi, Vijay, Ajay]
After invoking add(int index, E element) method: [Ravi, Gaurav, Vijay, Ajay]
After invoking addAll(Collection<? extends E> c) method:
[Ravi, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addAll(int index, Collection<? extends E> c) method:
[Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addFirst(E e) method:
[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addLast(E e) method:
[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat, Harsh]
51
Java LinkedList to remove Elements
Example Programs
import java.util.*;
public class LinkedList3 {
Output:
public static void main(String [] args)
{ Initial list of elements: []
LinkedList<String> ll=new LinkedList<String>(); After invoking add(E e) method: [R
ll.add("Ravi"); After invoking add(int index, E elem
ll.add("Vijay"); After invoking addAll(Collection<? e
ll.add("Ajay"); [Ravi, Gaurav, Vijay, Ajay, Sonoo, H
ll.add("Anuj"); After invoking addAll(int index, Coll
ll.add("Gaurav"); [Ravi, John, Rahul, Gaurav, Vijay, A
ll.add("Harsh"); After invoking addFirst(E e) method
ll.add("Virat"); [Lokesh, Ravi, John, Rahul, Gaurav
ll.add("Gaurav"); After invoking addLast(E e) method
ll.add("Harsh"); [Lokesh, Ravi, John, Rahul, Gaurav
ll.add("Amit");
System.out.println("Initial list of elements: "+ll);
//Removing specific element from arraylist
ll.remove("Vijay");
System.out.println("After invoking remove(object) method: "+ll); 52
Java LinkedList to remove Elements
Example Programs
//Removing element on the basis of specific position
ll.remove(0);
System.out.println("After invoking remove(index) method: "+ll);
LinkedList<String> ll2=new LinkedList<String>();
ll2.add("Ravi");
ll2.add("Hanumat");
// Adding new elements to arraylist
ll.addAll(ll2);
System.out.println("Updated list : "+ll);
//Removing all the new elements from arraylist
ll.removeAll(ll2);
System.out.println("After invoking removeAll() method: "+ll);
//Removing first element from the list
ll.removeFirst();
System.out.println("After invoking removeFirst() method: "+ll);
//Removing first element from the list
ll.removeLast();
System.out.println("After invoking removeLast() method: "+ll);
53
Java LinkedList to remove Elements
Example Programs
//Removing first occurrence of element from the list
ll.removeFirstOccurrence("Gaurav");
System.out.println("After invoking removeFirstOccurrence() method: "+ll);
//Removing last occurrence of element from the list
ll.removeLastOccurrence("Harsh");
System.out.println("After invoking removeLastOccurrence() method: "+ll);
54
Java LinkedList to remove Elements
Example Programs
Output:
Initial list of elements: [Ravi, Vijay, Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh,
Amit]
After invoking remove(object) method: [Ravi, Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav,
Harsh, Amit]
After invoking remove(index) method: [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav,
Harsh, Amit]
Updated list : [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit, Ravi, Hanumat]
After invoking removeAll() method: [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh,
Amit]
After invoking removeFirst() method: [Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]
After invoking removeLast() method: [Gaurav, Harsh, Virat, Gaurav, Harsh]
After invoking removeFirstOccurrence() method: [Harsh, Virat, Gaurav, Harsh]
After invoking removeLastOccurrence() method: [Harsh, Virat, Gaurav]
After invoking clear() method: []
55
Java LinkedList to remove Elements
Example Programs
//Removing first occurrence of element from the list
ll.removeFirstOccurrence("Gaurav");
System.out.println("After invoking removeFirstOccurrence() method: "+ll);
//Removing last occurrence of element from the list
ll.removeLastOccurrence("Harsh");
System.out.println("After invoking removeLastOccurrence() method: "+ll);
Page 33
56
Difference Between ArrayList and LinkedList
ArrayList LinkedList
1) ArrayList internally uses a dynamic LinkedList internally uses a doubly linked
array to store the elements. list to store the elements.
2) Manipulation with ArrayList Manipulation with LinkedList is faster than
is slow because it internally uses an array. ArrayList because it uses a doubly linked list,
If any element is removed from the array, all so no bit shifting is required in memory.
the other elements are shifted in memory.
3) An ArrayList class can act as a list only LinkedList class can act as a list and
because it implements List only. queue both because it implements List and
Deque interfaces.
4) ArrayList is better for storing and LinkedList is better for
accessing data. manipulating data.
5) The memory location for the elements of The location for the elements of a linked list
an ArrayList is contiguous. is not contagious.
6) Generally, when an ArrayList is initialized, There is no case of default capacity in a
a default capacity of 10 is assigned to the LinkedList. In LinkedList, an empty list is
ArrayList. created when a LinkedList is initialized.
7) To be precise, an ArrayList is a resizable LinkedList implements the doubly linked list
array. of the list interface.
57
Difference Between ArrayList and LinkedList
Points to Ponder
➢ Use List Collection classes if the order in which the element added
matters
➢ Use List when you want to perform insert, delete and update operations
based on particular positions in the list
➢ ArrayList, LinkedList and Vector all of them implement List interface
➢ LinkedList provides a better performance over ArrayList in insertion and
deletion operation.
➢ In case of frequent insertion and deletion operation, the choice can be
LinkedList than ArrayList
➢ Search operations are faster in ArrayList
➢ Both ArrayList and LinkedList are not synchronized
➢ Vector is synchronized
➢ If thread safety is not important, then we should choose either ArrayList
or LinkedList
58
Set Interface
Set Interface
60
HashSet
HashSet
62
HashSet
import java.util.*;
class HashSet1{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet();
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
set.add("Five");
Iterator<String> i=set.iterator(); Output:
Five
while(i.hasNext()) One
{ Four
System.out.println(i.next()); Two
} Three
} Note: The order of the objects printed
} are not predictable.
63
Constructors in Java HashSet Class
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, float It is used to initialize the capacity of the hash set to the given integer
loadFactor) 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.
64
Methods in Java HashSet Class
Sl. Modifier & Method Description
No. 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.
import java.util.*;
class HashSet2{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements Output:
Ajay
Iterator<String> itr=set.iterator();
Vijay
while(itr.hasNext()){ Ravi
System.out.println(itr.next());
} Note: HashSet doesn't allow duplicate
} elements.
}
66
HashSet Class – Example Program
Removing Elements
import java.util.*;
class HashSet3{
public static void main(String args[]){
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Arun");
set.add("Sumit");
System.out.println("An initial list of elements: "+set);
//Removing specific element from HashSet
set.remove("Ravi");
System.out.println("After invoking remove(object) method: "+set);
HashSet<String> set1=new HashSet<String>();
set1.add("Ajay");
set1.add("Gaurav");
set.addAll(set1);
System.out.println("Updated List: "+set);
67
HashSet Class – Example Program
Removing Elements
//Removing all the new elements from HashSet
set.removeAll(set1);
System.out.println("After invoking removeAll() method: "+set);
//Removing elements on the basis of specified condition
set.removeIf(str->str.contains("Vijay"));
System.out.println("After invoking removeIf() method: "+set);
//Removing all the elements available in the set
set.clear();
System.out.println("After invoking clear() method: "+set);
}
}
Output:
An initial list of elements: [Vijay, Ravi, Arun, Sumit]
After invoking remove(object) method: [Vijay, Arun, Sumit]
Updated List: [Vijay, Arun, Gaurav, Sumit, Ajay]
After invoking removeAll() method: [Vijay, Arun, Sumit]
After invoking removeIf() method: [Arun, Sumit]
After invoking clear() method:
68
HashSet Class – Example Program
Book
import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author,
String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
69
HashSet Class – Example Program
Book
public class HashSetExample {
public static void main(String[] args) {
HashSet<Book> set=new HashSet<Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar",
"BPB",8);
Book b2=new Book(102,"Data Communications & Networking",
"Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to HashSet
set.add(b1);
set.add(b2);
set.add(b3);
70
HashSet Class – Example Program
Book
//Traversing HashSet
for(Book b:set){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher
+" "+b.quantity);
}
}
}
Output:
101 Let us C Yashwant Kanetkar BPB 8
102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6
71
LinkedHashSet
LinkedHashSet Class
Note: Keeping the insertion order in the LinkedHashset has some additional
costs, both in terms of extra memory and extra CPU cycles. Therefore, if it is
not required to maintain the insertion order, go for the lighter-weight
HashMap or the HashSet instead.
73
LinkedHashSet Class
Constructor Description
HashSet() It is used to construct a default HashSet.
74
LinkedHashSet Class – Example Program
import java.util.*;
class LinkedHashSet1{
public static void main(String args[]){
//Creating HashSet and adding elements
LinkedHashSet<String> set=new LinkedHashSet();
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
set.add("Five");
Iterator<String> i=set.iterator();
while(i.hasNext())
Output:
{ One
System.out.println(i.next()); Two
} Three
} Four
} Five
75
LinkedHashSet Class – Example Program
Ignoring Duplicate Elements
import java.util.*;
class LinkedHashSet2{
public static void main(String args[]){
LinkedHashSet<String> al=new LinkedHashSet<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next()); Output:
} Ravi
Vijay
} Ajay
}
76
TreeSet
TreeSet Class
Constructor Description
TreeSet() It is used to construct an empty tree set that
will be sorted in ascending order according to
the natural order of the tree set.
79
Methods of 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 It is used to add all of the elements in the specified
addAll(Collection<? collection to this set.
extends E> c)
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.
Comparator<? super It returns a comparator that arranges elements in order.
E> comparator()
Iterator descendingIt It is used to iterate the elements in descending order.
erator()
NavigableSet descen It returns the elements in reverse order.
dingSet()
E floor(E e) It returns the equal or closest least element of the
specified element from the set, or null there is no such
element.
80
Methods of TreeSet Class
Method Description
SortedSet headSet(E It returns the group of elements that are less than the
toElement) specified element.
NavigableSet headSet( It returns the group of elements that are less than or equal
E toElement, boolean to(if, inclusive is true) the specified element.
inclusive)
E higher(E e) It returns the closest greatest element of the specified
element from the set, or null there is no such element.
81
Methods of TreeSet Class
Method Description
Spliterator spliterator() It is used to create a late-binding and fail-fast spliterator over
the elements.
NavigableSet subSet(E It returns a set of elements that lie between the given range.
fromElement, boolean
fromInclusive, E toElement,
boolean toInclusive)
SortedSet subSet(E It returns a set of elements that lie between the given range
fromElement, E toElement)) which includes fromElement and excludes toElement.
SortedSet tailSet(E It returns a set of elements that are greater than or equal to
fromElement) the specified element.
NavigableSet tailSet(E It returns a set of elements that are greater than or equal to
fromElement, boolean (if, inclusive is true) the specified element.
inclusive)
boolean contains(Object o) It returns true if this set contains the specified element.
boolean isEmpty() It returns true if this set contains no elements.
82
Methods of TreeSet Class
Method Description
boolean remove(Object o) It is used to remove the specified element from this set
if it is present.
void clear() It is used to remove all of the elements from this set.
83
TreeSet Class – Example Program
import java.util.*;
class TreeSet1{
public static void main(String args[]){
//Creating and adding elements
TreeSet<String> al=new TreeSet<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
//Traversing elements
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} Output:
} Ajay
} Ravi
Vijay
84
TreeSet Class – Example Program
import java.util.*;
class TreeSet2{
public static void main(String args[]){
TreeSet<String> set=new TreeSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ajay");
System.out.println("Traversing element through
Iterator in descending order");
Iterator i=set.descendingIterator(); Output:
while(i.hasNext()) Traversing element through Iterator in
{ descending order
System.out.println(i.next()); Vijay
Ravi
}
Ajay
Traversing element through
} NavigableSet in descending order
} Vijay
Ravi
85
Ajay
TreeSet Class – Example Program
import java.util.*;
class TreeSet3{
public static void main(String args[]){
TreeSet<Integer> set=new TreeSet<Integer>();
set.add(24);
set.add(66);
set.add(12);
set.add(15);
System.out.println("Lowest Value: "+set.pollFirst());
System.out.println("Highest Value: "+set.pollLast());
}
} Output:
Lowest Value: 12
Highest Value: 66
86
TreeSet Class – Example Program
import java.util.*;
class TreeSet4{
public static void main(String args[]){
TreeSet<String> set=new TreeSet<String>(); Output:
set.add("A"); Initial Set: [A, B, C, D, E]
set.add("B"); Reverse Set: [E, D, C, B, A]
set.add("C"); Head Set: [A, B, C]
set.add("D"); SubSet: [B, C, D, E]
set.add("E"); TailSet: [D, E]
System.out.println("Initial Set: "+set);
System.out.println("Reverse Set: "+set.descendingSet());
System.out.println("Head Set: "+set.headSet("C", true));
System.out.println("SubSet: "+set.subSet("A", false, "E", true));
System.out.println("TailSet: "+set.tailSet("C", false));
}
}
87
TreeSet Class – Example Program
import java.util.*;
class TreeSet5{
public static void main(String args[]){
TreeSet<String> set=new TreeSet<String>();
Output:
set.add("A");
Intial Set: [A, B, C, D, E]
set.add("B"); Head Set: [A, B]
set.add("C"); SubSet: [A, B, C, D]
set.add("D"); TailSet: [C, D, E]
set.add("E");
System.out.println("Intial Set: "+set);
System.out.println("Head Set: "+set.headSet("C"));
System.out.println("SubSet: "+set.subSet("A", "E"));
System.out.println("TailSet: "+set.tailSet("C"));
}
}
88
TreeSet Class – Example Program
import java.util.*;
class Book implements Comparable<
Book>{ // implementing the abstract method
int id; public int compareTo(Book b) {
String name,author,publisher; if(id>b.id){
int quantity; return 1;
public Book(int id, String name, Strin }else if(id<b.id){
g author, String publisher, int quantity) return -1;
{ }else{
this.id = id; return 0;
this.name = name; }
this.author = author; }
this.publisher = publisher; }
this.quantity = quantity;
}
89
TreeSet Class – Example Program
} 91
ClassCastException in TreeSet Class
Example Program
public class ClassCastExceptionTreeSet
{
// main method
public static void main(String[] argvs)
{
// creating objects of the class Employee
Employee obj1 = new Employee();
}
} 92
ClassCastException in TreeSet Class
Example Program
When we compile the above program, we get the ClassCastException, as shown
below.
93
Comparable Interface
Comparable Interface
//test.java
import java.util.*;
public class TestSort1{
public static void main(String args[]){
ArrayList<Student> al=new ArrayList<Student>();
al.add(new Student(101,"Vijay",23));
al.add(new Student(106,"Ajay",27));
al.add(new Student(105,"Jai",21));
Collections.sort(al);
for(Student st:al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
} Output:
} 105 Jai 21
101 Vijay 23
106 Ajay 27
97
Map Interface
Map Interface
•Map is an interface that stores data in the form of key value pair.
•All the keys in the map will be unique.
•We can retrieve the value stored in a map by providing the key value.
•A Map cannot contain duplicate values.
•Each key can map to atmost one value. There are two interfaces for
implementing Map in java :Map and SortedMap, and three classes: HashMap,
LinkedHashMap, and TreeMap.
•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.
•A Map can't be traversed, so you need to convert it into Set using keySet() or
entrySet() method.
99
Map Interface
Class Description
HashMap HashMap is the implementation of Map, but it doesn't
maintain any order.
LinkedHashMap LinkedHashMap is the implementation of Map. It inherits
HashMap class. It maintains insertion order.
TreeMap TreeMap is the implementation of Map and SortedMap. It
maintains ascending order.
100
Map Interface
Method Description
V put(Object key, It is used to insert an entry in the map.
Object value)
void putAll(Map It is used to insert the specified map in the map.
map)
V putIfAbsent(K key, It inserts the specified value with the specified key in the
V value) map only if it is not already specified.
Set<Map.Entry<K,V It returns the Set view containing all the keys and values.
>> entrySet()
void clear() It is used to reset the map. 101
Map Interface
Method Description
V compute(K key, It is used to compute a mapping for the specified key and its
BiFunction<? super K,? current mapped value (or null if there is no current mapping).
super V,? extends V>
remappingFunction)
boolean This method returns true if some value equal to the value
containsValue(Object exists within the map, else return false.
value)
boolean This method returns true if some key equal to the key exists
containsKey(Object key) within the map, else return false.
boolean equals(Object o) It is used to compare the specified Object with the Map.
void It performs the given action for each entry in the map until all
forEach(BiConsumer<? entries have been processed or the action throws an
super K,? super V> exception.
action)
V get(Object key) This method returns the object that contains the value
associated with the key. 102
Map Interface
Method Description
int hashCode() It returns the hash code value for the Map
boolean isEmpty() This method returns true if the map is empty; returns false if
it contains at least one key.
V merge(K key, V value, If the specified key is not already associated with a value or is
BiFunction<? super V,? associated with null, associates it with the given non-null
super V,? extends V> value.
remappingFunction)
V replace(K key, V value) It replaces the specified value for a specified key.
boolean replace(K key, V It replaces the old value with the new value for a specified
oldValue, V newValue) key.
void It replaces each entry's value with the result of invoking the
replaceAll(BiFunction<? given function on that entry until all entries have been
super K,? super V,? processed or the function throws an exception.
extends V> function)
Collection values() It returns a collection view of the values contained in the
map.
int size() This method returns the number of entries in the map. 103
Map.Entry Interface
Method Description
static <K extends Comparable<? It returns a comparator that compare the
super K>,V> objects in natural order on key.
Comparator<Map.Entry<K,V>>
comparingByKey()
static <K,V> It returns a comparator that compare the
Comparator<Map.Entry<K,V>> objects by key using the given Comparator.
comparingByKey(Comparator<?
super K> cmp)
static <K,V extends Comparable<? It returns a comparator that compare the
super V>> objects in natural order on value.
Comparator<Map.Entry<K,V>>
comparingByValue()
static <K,V> It returns a comparator that compare the
Comparator<Map.Entry<K,V>> objects by value using the given Comparator.
comparingByValue(Comparator<?
super V> cmp)
105
Java Map Example: Non-Generic (Old Style)
//Non-generic
import java.util.*;
public class MapExample1 {
public static void main(String[] args) {
Map map=new HashMap();
Output:
//Adding elements to map 1 Amit
map.put(1,"Amit"); 2 Jai
map.put(5,"Rahul");
map.put(2,"Jai");
5 Rahul
map.put(6,"Amit"); 6 Amit
//Traversing Map
Set set=map.entrySet();//Converting to Set so that we can traverse
Iterator itr=set.iterator();
while(itr.hasNext()){
//Converting to Map.Entry so that we can get key and value separately
Map.Entry entry=(Map.Entry)itr.next();
System.out.println(entry.getKey()+" "+entry.getValue());
}
}
}
106
Java Map Example: Generic (New Style)
import java.util.*;
class MapExample2{
public static void main(String args[]){
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
//Elements can traverse in any order
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
} Output:
} 102 Rahul
100 Amit
101 Vijay
107
Java Map Example: comparingByKey()
import java.util.*;
class MapExample3{
public static void main(String args[]){
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
//Returns a Set view of the mappings contained in this map
map.entrySet()
//Returns a sequential Stream with this collection as its source
.stream()
//Sorted according to the provided Comparator
.sorted(Map.Entry.comparingByKey()) Output:
//Performs an action for each element of this stream
.forEach(System.out::println); 100=Amit
} 101=Vijay
} 102=Rahul
108
Java Map Example: comparingByKey()
in Descending Order
import java.util.*;
class MapExample4{
public static void main(String args[]){
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
//Returns a Set view of the mappings contained in this map
map.entrySet()
//Returns a sequential Stream with this collection as its source
.stream()
//Sorted according to the provided Comparator
.sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
//Performs an action for each element of this stream
.forEach(System.out::println);
} Output:
} 102=Rahul
101=Vijay
100=Amit 109
Java Map Example: comparingByValue()
import java.util.*;
class MapExample5{
public static void main(String args[]){
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
//Returns a Set view of the mappings contained in this map
map.entrySet()
//Returns a sequential Stream with this collection as its source
.stream()
//Sorted according to the provided Comparator
.sorted(Map.Entry.comparingByValue())
//Performs an action for each element of this stream
.forEach(System.out::println); Output:
} 100=Amit
}
102=Rahul
101=Vijay 110
HashMap Class
HashMap Class
➢ HashMap uses the hashcode value of an object to determine how the object
should be stored in the collection.
➢ Hashcode is used again to help locate the object in the collection.
➢ Gives you an unsorted and unordered Map.
➢ Allows one null key and multiple null values in a collection.
➢ HashMap are not synchronized
➢ Map is an object that stores key/value pairs. Given a key, you can find its value.
➢ Keys must be unique, but values may be duplicated.
➢ The HashMap class provides the primary implementation of the map interface.
➢ The HashMap class uses a hashtable to implement Map interface.
➢ This allows the execution time of basic operations, such as get() and put() to
be constant.
112
Java HashMap Example: No Duplicate Key
import java.util.*;
public class HashMapExample2{
public static void main(String args[]){
HashMap<Integer,String> map=new HashMap<Integer,String>();/
/Creating HashMap
map.put(1,"Mango"); //Put elements in Map
map.put(2,"Apple");
map.put(3,"Banana");
map.put(1,"Grapes"); //trying duplicate key
System.out.println("Iterating Hashmap...");
for(Map.Entry m : map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
} Output:
} Iterating Hashmap...
} 1 Grapes
2 Apple
3 Banana 113
Java HashMap Example: add() elements
import java.util.*;
class HashMap1{
public static void main(String args[]){
HashMap<Integer,String> hm=new HashMap<Integer,String>();
System.out.println("Initial list of elements: "+hm);
hm.put(100,"Amit");
hm.put(101,"Vijay");
hm.put(102,"Rahul");
hm.putIfAbsent(103, "Gaurav");
System.out.println("After invoking putIfAbsent() method ");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
HashMap<Integer,String> map=new HashMap<Integer,String>();
map.put(104,"Ravi");
map.putAll(hm);
System.out.println("After invoking putAll() method ");
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
115
Java HashMap Example: add() elements
Output:
Initial list of elements: {}
After invoking put() method
100 Amit
101 Vijay
102 Rahul
After invoking putIfAbsent() method
100 Amit
101 Vijay
102 Rahul
103 Gaurav
After invoking putAll() method
100 Amit
101 Vijay
102 Rahul
103 Gaurav
104 Ravi
116
Java HashMap Example: to remove() elements
import java.util.*;
public class HashMap2 {
public static void main(String args[]) {
HashMap<Integer,String> map=new HashMap<Integer,String>();
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
map.put(103, "Gaurav");
System.out.println("Initial list of elements: "+map);
//key-based removal
map.remove(100);
System.out.println("Updated list of elements: "+map);
//value-based removal
map.remove(101);
System.out.println("Updated list of elements: "+map);
//key-value pair based removal
map.remove(102, "Rahul");
System.out.println("Updated list of elements: "+map);
}
} 117
Java HashMap Example: to remove() elements
Output:
118
Java HashMap Example: to replace() elements
import java.util.*;
class HashMap3{
public static void main(String args[]){
HashMap<Integer,String> hm=new HashMap<Integer,String>();
hm.put(100,"Amit");
hm.put(101,"Vijay");
hm.put(102,"Rahul");
System.out.println("Initial list of elements:");
for(Map.Entry m:hm.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
119
Java HashMap Example: to replace() elements
System.out.println("Updated list of elements:");
hm.replace(102, "Gaurav");
for(Map.Entry m:hm.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
System.out.println("Updated list of elements:");
hm.replace(101, "Vijay", "Ravi");
for(Map.Entry m:hm.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
System.out.println("Updated list of elements:");
hm.replaceAll((k,v) -> "Ajay");
for(Map.Entry m:hm.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
}
} 120
Java HashMap Example: to replace() elements
Output:
Initial list of elements:
100 Amit
101 Vijay
102 Rahul
Updated list of elements:
100 Amit
101 Vijay
102 Gaurav
Updated list of elements:
100 Amit
101 Ravi
102 Gaurav
Updated list of elements:
100 Ajay
101 Ajay
102 Ajay
121
Java HashMap Example: Book
import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int q
uantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
122
Java HashMap Example: Book
123
Java HashMap Example: Book
//Traversing map
for(Map.Entry<Integer, Book> entry:map.entrySet()){
int key=entry.getKey();
Book b=entry.getValue();
System.out.println(key+" Details:");
System.out.println(b.id+" "+b.name+" "+b.author+" "+
b.publisher+" "+b.quantity);
}
}
} Output:
1 Details:
101 Let us C Yashwant Kanetkar BPB 8
2 Details:
102 Data Communications and Networking Forouzan Mc Graw Hill 4
3 Details:
103 Operating System Galvin Wiley 6
124
LinkedHashMap Class
LinkedHashMap Class
126
Java LinkedHashMap Example
import java.util.*;
class LinkedHashMap1{
public static void main(String args[]){
LinkedHashMap<Integer,String> hm
=new LinkedHashMap<Integer,String>();
hm.put(100,"Amit");
hm.put(101,"Vijay");
hm.put(102,"Rahul");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
} Output:
} 100 Amit
101 Vijay
102 Rahul
127
Java LinkedHashMap Example – Key-Value Pair
import java.util.*;
class LinkedHashMap2{
public static void main(String args[]){
LinkedHashMap<Integer, String> map =
new LinkedHashMap<Integer, String>();
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
//Fetching key
System.out.println("Keys: "+map.keySet());
//Fetching value
System.out.println("Values: "+map.values());
//Fetching key-value pair
System.out.println("Key-Value pairs: "+map.entrySet());
} Output:
} Keys: [100, 101, 102]
Values: [Amit, Vijay, Rahul]
Key-Value pairs: [100=Amit, 101=Vijay, 102=Rahul] 128
Java LinkedHashMap Example – remove()
import java.util.*;
public class LinkedHashMap3 {
public static void main(String args[]) {
Map<Integer,String> map
=new LinkedHashMap<Integer,String>();
map.put(101,"Amit");
map.put(102,"Vijay");
map.put(103,"Rahul");
System.out.println("Before invoking remove() method: "+map);
map.remove(102);
System.out.println("After invoking remove() method: "+map);
}
}
Output:
Before invoking remove() method: {101=Amit, 102=Vijay,
103=Rahul}
After invoking remove() method: {101=Amit, 103=Rahul}
129
Java LinkedHashMap Example – Book
import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int q
uantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
130
Java LinkedHashMap Example – Book
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
131
Java LinkedHashMap Example – Book
//Traversing map
for(Map.Entry<Integer, Book> entry:map.entrySet()){
int key=entry.getKey();
Book b=entry.getValue();
System.out.println(key+" Details:");
System.out.println(b.id+" "+b.name+" "+b.author+" "+
b.publisher+" "+b.quantity);
}
}
}
Output:
2 Details:
102 Data Communications & Networking Forouzan Mc Graw Hill 4
1 Details:
101 Let us C Yashwant Kanetkar BPB 8
3 Details:
103 Operating System Galvin Wiley 6
132
HashTable Class
HashTable Class
134
Java HashTable Example
import java.util.*;
class Hashtable1{
public static void main(String args[]){
Hashtable<Integer,String> hm=new Hashtable<Integer,String>();
hm.put(100,"Amit");
hm.put(102,"Ravi");
hm.put(101,"Vijay");
hm.put(103,"Rahul");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
} Output:
} 103 Rahul
102 Ravi
101 Vijay
100 Amit
135
TreeMap Class
TreeMap Class
137
Java TreeMap Example
import java.util.*;
class TreeMap1{
public static void main(String args[]){
TreeMap<Integer,String> map=new TreeMap<Integer,String>();
map.put(100,"Amit");
map.put(102,"Ravi");
map.put(101,"Vijay");
map.put(103,"Rahul");
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
} Output:
100 Amit
101 Vijay
102 Ravi
103 Rahul
138
Properties Class
Properties Class
➢ 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 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. 140
Properties Class - Constructors
141
Example of Properties class to get all the system
properties
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args)throws Exception{
Properties p=System.getProperties();
Set set=p.entrySet();
Iterator itr=set.iterator();
while(itr.hasNext()){
Map.Entry entry=(Map.Entry)itr.next();
System.out.println(entry.getKey()+" = “ +entry.getValue());
} }} Output:
java.runtime.name = Java(TM) SE Runtime Environment
sun.boot.library.path = C:\Program Files\Java\jdk1.7.0_01\jre\bin
java.vm.version = 21.1-b02
java.vm.vendor = Oracle Corporation
java.vendor.url = http://java.oracle.com/
path.separator = ;
java.vm.name = Java HotSpot(TM) Client VM
file.encoding.pkg = sun.io
user.country = US
user.script =
sun.java.launcher = SUN_STANDARD 142
Queue Interface
Queue Interface
➢ The interface Queue is available in the java.util package and does extend the
Collection interface.
➢ It is used to keep the elements that are processed in the First In First Out (FIFO)
manner.
➢ It is an ordered list of objects, where insertion of elements occurs at the end of
the list, and removal of elements occur at the beginning of the list.
➢ Being an interface, the queue requires, for the declaration, a concrete class, and
the most common classes are the LinkedList and PriorityQueue in Java.
➢ Implementations done by these classes are not thread safe.
➢ If it is required to have a thread safe implementation, PriorityBlockingQueue is an
available option.
144
Queue Interface - Features
➢ FIFO concept is used for insertion and deletion of elements from a queue.
➢ The Java Queue provides support for all of the methods of the Collection interface
including deletion, insertion, etc.
➢ PriorityQueue, ArrayBlockingQueue and LinkedList are the implementations that
are used most frequently.
➢ The NullPointerException is raised, if any null operation is done on the
BlockingQueues.
➢ Those Queues that are present in the util package are known as Unbounded
Queues.
➢ Those Queues that are present in the util.concurrent package are known as
bounded Queues.
➢ All Queues barring the Deques facilitates removal and insertion at the head and
tail of the queue; respectively. In fact, deques support element insertion and
removal at both ends. 145
Methods in Queue Interface
Method Description
boolean It is used to insert the specified element into this
add(object) queue and return true upon success.
boolean It is used to insert the specified element into this
offer(object) queue.
Object It is used to retrieves and removes the head of this
remove() queue.
Object poll() It is used to retrieves and removes the head of this
queue, or returns null if this queue is empty.
146
PriorityQueue Class
PriorityQueue Class
➢ PriorityQueue is also class that is defined in the collection framework that gives
us a way for processing the objects on the basis of priority.
➢ Insertion and deletion of objects follows FIFO pattern in the Java queue.
➢ However, sometimes the elements of the queue are needed to be processed
according to the priority, that's where a PriorityQueue comes into action.
148
Java PriorityQueue Example
Output:
head:Amit
head:Amit
iterating the queue elements:
Amit
Jai
Karan
Vijay
Rahul
after removing two elements:
Karan
Rahul
Vijay
150
DeQueue Interface
DeQueue Interface - Features
152
DeQueue Interface - Methods
Methods Description
add(E e) This method is used to insert a specified element into
the queue represented by the deque
addAll(Collection<? Adds all the elements in the specified collection at the
Extends E>c) end of the deque.
addFirst(E e) Inserts the specified element at the front of the deque.
addLast(E e) Inserts the specified element at the end of the deque.
contains(object o) Returns true if the deque contains the specified
element.
descendingIterator() Returns an iterator over the elements in reverse
sequential order.
element() Retrieves the head of the queue represented by the
deque.
getFirst() Retrieves but does not remove the first element of the
deque.
getLast() Retrieves but does not remove the last element of the
deque.
153
DeQueue Interface - Methods
Methods Description
iterator() Returns an iterator over the element in the deque in a
proper sequence.
offer(E e) Inserts the specified element into the deque, returning
true upon success and false if no space is available.
offerFirst() Inserts the specified element at the front of the deque
unless it violates the capacity restriction.
offerLast() Inserts the specified element at the end of the deque
unless it violates the capacity restriction.
peek() Retrieves but does not move the head of the queue
represented by the deque or may return null if the
deque is empty.
peekFirst() Retrieves but does not move the first element of the
deque or may return null if the deque is empty.
peekLast() Retrieves but does not move the last element of the
deque or may return null if the deque is empty.
154
DeQueue Interface - Methods
Methods Description
poll() Retrieves and remove the head of the queue
represented by the deque or may return null if the
deque is empty.
pollFirst() Retrieves and remove the first element of the deque or
may return null if the deque is empty.
pollLast() Retrieves and remove the last element of the deque or
may return null if the deque is empty.
pop() Pops an element from the stack represented by the
deque.
push() Pushes an element onto the stack represented by the
deque.
remove() Retrieves and remove the head of the queue
represented by the deque.
removeLastOccurre Remove the last occurrence of the element from the
nce(Object o) deque. 155
DeQueue Interface - Methods
Methods Description
removeLast() Retrieve and remove the last element from the deque.
removeLastOccurre Remove the last occurrence of the element from the
nce(Object o) deque.
size() Returns the total number of elements in the deque.
156
ArrayDeque Class
ArrayDeque Class
158
ArrayDeque Class - Example
import java.util.*;
public class ArrayDequeExample{
public static void main(String[] args){
//Creating Deque and adding elements
Deque<String> deque=new ArrayDeque<String>();
deque.add("Ravi");
deque.add("Vijay");
deque.add("Ajay");
//Traversing elements
for(String str:deque){ Output:
System.out.println(str); Ravi
} Vijay
} Ajay
}
159
ArrayDeque Class – Example
offerFirst(), pollLast()
Import java.util.*;
Public class DequeExample{
Public static void main(String[] args){
Deque<String> deque=new ArrayDeque<String>();
deque.offer("arvind");
deque.offer("vimal");
deque.add("mukul");
deque.offerFirst("jai");
System.out.println("After offerFirst Traversal...");
for(String s:deque){ Output:
System.out.println(s); After offerFirst Traversal...
} jai
deque.pollLast(); arvind
System.out.println("After pollLast() Traversal..."); vimal
for(String s:deque){ mukul
System.out.println(s); After pollLast() Traversal...
} jai
} arvind
} Vimal
160
Utility Class
Utility Class
➢ A utility class in Java is a class that provides static methods that are accessible
for use across an application. The static methods in utility classes are used for
performing common routines in our application.
➢ Utility classes cannot be instantiated and are sometimes stateless without static
variables. We declare a utility class as final, and all its methods must be static.
➢ Since we don’t want our utility classes to be instantiated, a private constructor
is introduced. Having a private constructor means that Java won’t create a
default constructor for our utility class. The constructor can be empty.
➢ The purpose of a utility class is to provide methods for executing certain
functionalities within a program, while the main class focuses on the core
problem it solves.
➢ Methods of a utility are accessed via the classname. It makes our code more
flexible for use while remaining modular.
162
Utility Class
163
Create Utility Class - Example
164
THANK YOU
https://www.javatpoint.com/java-deque
Page 70