Unit-II
Collection Framework:
The Collection Framework in Java is a unified architecture for storing and
manipulating groups of objects. It provides ready-made classes and interfaces
that make it easier to work with data collections such as lists, sets, queues, and
maps.
The goal of the Java Collection Framework (JCF) is to provide a
standardized and efficient way to store, manage, and manipulate groups of
objects.
Benefits of the Java Collection Framework
1. Reduces Coding Effort
o Provides ready-made classes such as ArrayList, LinkedList, and
HashMap, so developers don't need to implement data structures
from scratch.
2. Improves Performance
o Includes efficient and optimized implementations of common data
structures and algorithms.
3. Code Reusability
o Collection classes can be reused in different applications, reducing
development time.
4. Standardized API
o Common interfaces such as List, Set, and Map provide a consistent
way to work with data.
5. Easy Data Manipulation
o Supports operations like adding, removing, searching, sorting, and
updating elements easily.
6. Dynamic Memory Management
o Collections can grow or shrink automatically as data changes.
Collection classes: Collection classes are the classes in the Java Collection
Framework that implement collection interfaces and provide different ways to
store, retrieve, and manipulate data. Examples include ArrayList, LinkedList,
HashSet, TreeSet, HashMap, and PriorityQueue.
Main Collection Classes
1. ArrayList
Implements the List interface.
Stores elements in insertion order.
Allows duplicate elements.
Fast for data retrieval.
2. LinkedList
Implements List interface.
Uses a doubly linked list structure.
Efficient for insertion and deletion.
3. HashSet
Implements Set interface.
Does not allow duplicate elements.
Does not maintain insertion order.
4. TreeSet
Stores elements in sorted order.
Does not allow duplicates.
Collection interfaces: Collection interfaces define the structure and behavior
of different types of collections in the Java Collection Framework. They specify
what operations can be performed on collections.
Main Collection Interfaces
1. Collection
o Root interface of the Collection Framework.
o Represents a group of objects.
2. List
o Ordered collection.
o Allows duplicate elements.
o Example implementations: ArrayList, LinkedList.
3. Set
o Does not allow duplicate elements.
o Example implementations: HashSet, TreeSet.
4. Queue
o Stores elements before processing.
o Generally follows FIFO (First In, First Out).
o Example implementation: PriorityQueue.
5. Deque
o Double-ended queue.
o Elements can be inserted and removed from both ends.
6. Map
o Stores data as key-value pairs.
o Not a child of Collection interface.
o Example implementations: HashMap, TreeMap.
Methods of List interface
Method Description
add(E e) Adds an element to the list
(E is a generic type parameter
representing the type of element the
collection stores.)
Ex: [Link]("Java");
get(int index) Retrieves an element from a specified
position
Ex: String s = [Link](0);
set(int index, E element) Replaces an element at a specified
position
Ex: [Link](0, "Python");
remove(int index) Removes an element from a specified
position
Ex: [Link](0);
size() Returns the number of elements in the
list
Ex: int n = [Link]();
Methods of the Queue Interface
The Queue interface is used to store elements in a queue, typically following
the FIFO (First In, First Out) principle.
Method Description
add(E e) Inserts an element into the queue.
Throws an exception if insertion
fails.
remove() Removes and returns the head (front)
element. Throws an exception if the
queue is empty.
peek() Returns the head(front) element
without removing it. Returns null if
the queue is empty.
Removes and returns the head
Poll() element. Returns null if the queue is
empty.
Ex: Queue<Integer> q = new LinkedList<>();
[Link](10);
[Link](20);
[Link](30);
[Link]([Link]()); // 10
[Link]([Link]()); // 10
[Link]([Link]()); // 20
Methods of the Deque Interface
The Deque (Double-Ended Queue) interface allows elements to be inserted
and removed from both the front and rear of the queue.
Method Description
addFirst(E e) Inserts an element at the front of the deque.
addLast(E e) Inserts an element at the rear of the deque.
removeFirst() Removes and returns the first element.
removeLast() Removes and returns the last element.
getFirst() Returns the first element without removing it.
Example:
import [Link].*;
public class Main {
public static void main(String[] args) {
Deque<Integer> dq = new ArrayDeque<>();
[Link](10);
[Link](20);
[Link](30);
[Link]([Link]()); // 10
[Link]([Link]()); // 10
[Link]([Link]()); // 30
}
Iterator: An Iterator is an interface used to traverse (access) elements one by
one in a collection such as a List or Set.
Key Methods of Iterator
1. hasNext() → Checks if more elements are available in the list or set
2. next() → Returns the next element
3. remove() → Removes the current element (optional method)
Ex:
import [Link].*;
public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Mango");
Iterator<String> it = [Link]();
while ([Link]())
{
[Link]([Link]());
}
}
}
OUTPUT: Apple
Banana
Mango
Difference between hasNext() and next() in Java Iterator
Both methods are used in the Iterator to traverse elements in collections like
List or Set.
1. hasNext( )
Checks whether there are more elements left in the collection.
Returns:
o true → if next element exists
o false → if no more elements
Does not move the cursor.
Ex: [Link]();
2. next()
Returns the next element in the collection.
Moves the cursor forward.
Throws exception if no element exists.
Example: [Link]();
Explain the usage of the for-each loop in java when working with
collections. Compare and contrast the for each loop with the traditional
approach using an iterator
When working with Java collections, there are two common ways to traverse all
elements:
1. Enhanced for loop (for-each loop)
2. Iterator
1. For-each Loop: In programming, a for-each loop (also called an enhanced
for loop) is used to iterate through all elements of a collection or array without
managing an index manually.
Syntax:
for (ElementType element : collection)
{
// use element
}
Example:
List<String> names = new ArrayList<>();
[Link]("Alice");
[Link]("Bob");
[Link]("Charlie");
for (String name : names) {
[Link](name);
}
The compiler converts the for-each loop into code that uses an Iterator behind
the scenes:
Iterator<String> it = [Link]();
while ([Link]())
{
String name = [Link]();
[Link](name);
}
So the for-each loop is essentially a simplified syntax for iteration.
2. Traditional Iterator Approach: Traditional Iterator Approach used to traverse
(access) elements one by one in a collection such as a List or Set.
Key Methods of Iterator
1. hasNext() → Checks if more elements are available in the list or set
2. next() → Returns the next element
3. remove() → Removes the current element (optional method)
List<String> names = new ArrayList<>();
[Link]("Alice");
[Link]("Bob");
[Link]("Charlie");
Iterator<String> it = [Link]();
while ([Link]())
{
[Link]([Link]());
}
How vector is differ from arraylist
Vector and ArrayList are both resizable array implementations in Java, and
both maintain insertion order and allow random access by index. The main
differences are related to synchronization, performance, and historical
usage.
Synchronization
Vector is synchronized (thread-safe).
ArrayList is not synchronized.
Performance
Vector is generally slower because every method call involves
synchronization.
ArrayList is faster in single-threaded environments.
Legacy Methods
Vector contains legacy methods such as: addElement(), elementAt().
ArrayList uses only Collection Framework methods: add(), get().
Enumeration Support
Vector supports the old Enumeration interface.
ArrayList does not support Enumeration directly.
Recommended Usage
Vector is mainly used in legacy applications.
ArrayList is the preferred choice in modern Java development.
MVC Architecture in Java
What is MVC architecture in Java?
The Model-View-Controller (MVC) architecture in Java is a design pattern that
provides a structured approach for developing applications. It separates the
application’s concerns into three main components: the model, the view, and the
controller. Each component has a specific role and responsibility within the
architecture.
Model: The model represents the data and business logic of the application. It
encapsulates the application’s data and provides methods for accessing,
manipulating, and updating that data. The model component is independent of
the user interface and focuses solely on the application’s functionality.
View: The view is responsible for rendering the user interface and displaying
the data to the user. It presents the data from the model to the user in a visually
appealing and understandable way. The view component does not contain any
business logic but instead relies on the model for data.
Controller: The controller acts as an intermediary between the model and the
view. It handles user input, processes user actions, and updates the model or
view accordingly. The controller interprets user actions and triggers the
appropriate methods in the model or view. It ensures the separation of concerns
by keeping the view and model independent of each other.
In Java programming, the Model comprises basic Java classes that encapsulate
data and business logic. The View is responsible for presenting the data to the
user interface, while the Controller consists of servlets that handle user requests.
This clear separation of components enables the following processing flow for
user requests:
In the context of the server-client architecture, the process of handling a page
request can be described as follows:
A client, typically a web browser, initiates a request and sends it to the server-
side controller.
The controller receives the request and interacts with the model component. It
retrieves the necessary data from the model, which may involve processing and
manipulating the data as required.
Once the controller has gathered the requested data, it transfers this data to the
view layer.
The view layer, utilizing the provided data, generates the appropriate output
or representation of the requested page. Finally, the generated result is sent back
to the client’s browser, completing the request-response cycle. Advantages of
MVC Architecture in Java.
The MVC (Model-View-Controller) architecture offers several advantages
in Java development:
Separation of Concerns: MVC promotes a clear separation of concerns
between the model, view, and controller components. This separation allows for
better code organization, improved modularity, and easier maintenance.
Developers can focus on specific aspects of the application without impacting
other components.
Code Reusability: By separating the concerns into distinct components, code
reuse becomes more feasible. The model can be reused across different views,
and multiple views can be created for a single model. This reusability reduces
duplication of code and improves development efficiency.
Simultaneous Development: MVC allows multiple developers to work
simultaneously on different components. The model, view, and controller can
be developed independently as long as they adhere to the defined interfaces and
communication protocols. This parallel development approach accelerates the
overall development process.
Flexibility and Extensibility: MVC provides flexibility by allowing changes
in one component without affecting others. For example, modifying the view
does not require altering the model or controller. This flexibility also enables
the easy addition of new views or controllers to enhance the application’s
functionality.
Testability: The separation of concerns in MVC makes unit testing and
debugging more manageable. Each component can be independently tested, as
they have well-defined responsibilities and interfaces. This promotes
comprehensive testing, reduces dependencies, and improves the overall quality
of the application.
Enhanced User Experience: With MVC, the view layer handles the
presentation of data to the user. This separation allows for greater control over
the user interface and enables the use of different views for different platforms
or devices. Developers can create responsive and user-friendly interfaces
tailored to specific user needs.
Support for Maintainability: MVC simplifies the maintenance of
applications over time. Changes can be made to individual components without
requiring extensive modifications to the entire system. This modularity
enhances maintainability and reduces the risk of introducing bugs or breaking
existing functionality.
Implementation of MVC using Java
To implement a web application based on MVC design pattern, we will create
Course Class, which acts as the model layer
CourseView Class, which defines the presentation layer (view layer)
CourseContoller Class, which acts as a controller
Now, let’s explore these layers one by one.
The Model Layer In the MVC design pattern, the model is the data layer
which defines the business logic of the system and also represents the state
of the application. The model objects retrieve and store the state of the model
in a database. Through this layer, we apply rules to data, which eventually
represents the concepts our application manages. Now, let’s create a model
using StudentModel Class.
public class StudentModel
{
private String rolno, name;
private int m1, m2, m3;
public StudentModel(String rolno, String name, int m1, int m2, int m3)
{
[Link] = rolno;
[Link] = name;
this.m1 = m1;
this.m2 = m2;
this.m3 = m3;
}
public String getRolno()
{
return rolno;
}
public void setRolno(String rolno)
{
[Link] = rolno;
}
public String getName()
{
return name;
}
public void setName(String name)
{
[Link] = name;
}
public int getM1()
{
return m1;
}
public void setM1(int m1)
{
this.m1 = m1;
}
public int getM2()
{
return m2;
}
public void setM2(int m2)
{
this.m2 = m2;
}
public int getM3()
{
return m3;
}
public void setM3(int m3)
{
this.m3 = m3;
}
public String getResult()
{
String result="";
if(m1=75)
{
result="Distinction";
}
else if(per>=60)
{
result="First Class";
}
else if(per>=50)
{
result="Second Class";
}
else if(per>=35)
{
result="Third Class";
}
else
{
result="Fail";
}
}
return result;
}
public String getGrade()
{
double per=((m1+m2+m3)/3);
String grade="";
if(per>=90)
{
grade="A";
}else if(per>=80)
{
grade="B";
}else if(per>=70)
{
grade="C";
}else if(per>=60)
{
grade="D";
}else{
grade="E";
}
return grade;
}
}
The View Layer
This layer of the MVC design pattern represents the output of the application or
the user interface. It displays the data fetched from the model layer by the
controller and presents the data to the user whenever asked for. It receives all
the information it needs from the controller and it doesn’t need to interact with
the business layer directly. Let’s create a view using StudentView Class.
public class StudentView
{
public void displayResult(String rNo,String sName, int m1, int m2, int
m3, String result, String grade)
{
[Link]("---------------------------------------------------");
[Link]("RollNo\tName\t\tMarks1\tMarks2\tMarks3\tRe
sult\t\tGrade");
[Link]("--------------------------------------------------------
----------------");
[Link](rNo+"\t"+sName+"\t"+m1+"\t"+m2+"\t"+m3+"
\t"+result+"\t"+grade);
[Link]("----------------------------------------------------");
}
}
The Controller Layer
The Controller is like an interface between Model and View. It receives the user
requests from the view layer and processes them, including the necessary
validations. The requests are then sent to model for data processing. Once they
are processed, the data is again sent back to the controller and then displayed on
the view. Let’s create StudentContoller Class which acts as a controller.
public class StudentController
{
private StudentModel model;
private StudentView view;
public StudentController(StudentModel model, StudentView view)
{
[Link] = model;
[Link] = view;
}
public void UpdateView()
{
[Link]([Link](),[Link](),model.getM1(),m
odel.getM2(),[Link] tM3(),[Link](),[Link]());
}
}
This controller class is just responsible for calling the model to get/set the data
and updating the view based on that.
Main Java Class Let’s call this class “[Link]”. Check out the
code below.
public class MVCPatternDemo
{
public static void main(String[] args)
{
String rNo,sName; int m1,m2,m3;
Scanner in=new Scanner([Link]);
[Link]("Enter Roll No:");
rNo=[Link]();
[Link]("Enter Name:");
sName=[Link]();
[Link]("Marks in three subjects:");
m1=[Link]();
m2=[Link]();
m3=[Link]();
StudentModel sm=new StudentModel(rNo, sName, m1, m2, m3);
StudentView sv=new StudentView();
StudentController sc=new StudentController(sm, sv);
[Link]();
}
}