Unit Iii Ajava
Unit Iii Ajava
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.
In core java, there are mainly three types of design patterns, which are further divided into their
sub-parts:
1. Factory Pattern
2. Abstract Factory Pattern
3. Singleton Pattern
4. Prototype Pattern
5. Builder Pattern.
1. Adapter Pattern
2. Bridge Pattern
3. Composite Pattern
4. Decorator Pattern
5. Facade Pattern
6. Flyweight Pattern
7. Proxy Pattern
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:
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.
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.
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.
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.
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.
It is used:
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
According to GoF, a Proxy Pattern "provides the control for accessing the original object".
It is used:
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.
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 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.
Benefits:
The components don't need to contain logic to deal with their intercommunication and
therefore, they are more generic.
Usage:
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.
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:
Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class
and implements List interface.
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.
Constructor Description
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)
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(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.
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]
Constructor Description
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.
E get(int index) It is used to return the element at the specified position 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
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.
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.
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 HashSet class extends AbstractSet class which implements Set interface. The Set interface
inherits Collection and Iterable interfaces in hierarchical order.
SN Constructor Description
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.
2) void clear() It is used to remove all of the elements from the 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.
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 is a Hashtable and Linked list implementation of the set interface. It
inherits HashSet class and implements Set interface.
Constructor Description
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 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.
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.
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.
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.
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.
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.
public void sort(List list): It is used to sort the elements of List. List elements must be of the
Comparable type.
File: Student.java
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
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.
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.
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.