0% found this document useful (0 votes)
14 views31 pages

Mtech Adsa Unit2

Advance data structure
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views31 pages

Mtech Adsa Unit2

Advance data structure
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

I.

STACK
A linear data structure called a stack is used to store an ordered, linear sequence of elements.
It is a type of abstract data. A stack operates according to the Last In First Out (LIFO)
principle, which states that the element that was added last will be deleted first. Because we
can only access the elements on the top of the Stack, it is necessary to maintain a pointer to
the top of the Stack, which is the last element to be placed, in order to implement the Stack.

Stack Operation:
1. PUSH: The insertion of a new element into a stack is implied by the PUSH operation. The
top of the stack is always where a new element is added, so we must always check to see if it
is empty by using the formula TOP=Max-1. In the case that this condition is false, the Stack is
full and no other elements may be added. Even if we attempt to add the element, a Stack
overflow message will be shown.
Algorithm:
Step-1: If TOP = Max-1
Print “Overflow”
Goto Step 4
Step-2: Set TOP= TOP + 1
Step-3: Set Stack[TOP]= ELEMENT
Step-4: END
2. POP: POP denotes removing a stack element. Make sure to verify that the Stack Top is
NULL, i.e., TOP=NULL, before deleting an element. In the event that this condition is met,
the Stack will be empty, making deletion operations impossible. Even if deletion attempts are
made, the Stack Underflow warning will be produced.
Algorithm:
Step-1: If TOP= NULL
Print “Underflow”
Goto Step 4
Step-2: Set VAL= Stack[TOP]
Step-3: Set TOP= TOP-1
Step-4: END
3. PEEK: The Peek operation is employed when it is necessary to return the value of the
topmost stack element without erasing it. This operation first determines whether the Stack is
empty, i.e., TOP = NULL; if it is, then the value will be returned; otherwise, an appropriate
notice will be displayed.
Algorithm:
Step-1: If TOP = NULL
PRINT “Stack is Empty”
Goto Step 3
Step-2: Return Stack[TOP]
Step-3: END
Representation of the Stack
A stack may have a set, predetermined size or it may be dynamic, meaning that the size of the
stack may fluctuate over time. Pointer, Array, Structure, and Linked List can all be used to
represent it.
Application of Stack in Data Structure are as following:
 Evaluation of Arithmetic Expressions
 Backtracking
 Delimiter Checking
 Reverse a Data
 Processing Function Calls
1. Evaluation of Arithmetic Expressions
In computer languages, a stack is an extremely efficient data structure for evaluating
arithmetic statements. Operands and operators are the components of an arithmetic
expression.
The arithmetic expression may additionally contain parenthesis such as "left parenthesis" and
"right parenthesis," in addition to operands and operators.
Example: A + (B – C)
The normal precedence rules for arithmetic expressions must be understood in order to
evaluate the expressions. The following are the five fundamental arithmetic operators’
precedence rules:

Operators Associativity Precedence

Highest followed by *Multiplication


^ exponentiation Right to left
and /division

*Multiplication, Highest followed by + addition and –


Left to right
/division subtraction
Operators Associativity Precedence

+ addition, –
Left to right lowest
subtraction

Evaluation of Arithmetic Expression requires two steps:


1. Put the provided expression first in special notation.
2. In this new notation, evaluate the expression.
Notations for Arithmetic Expression
There are three notations to represent an arithmetic expression:
 Infix Notation
 Prefix Notation
 Postfix Notation
Infix Notation
Each operator is positioned between the operands in an expression written using the infix
notation. Depending on the requirements of the task, infix expressions may be parenthesized
or not.
Example: A + B, (C – D) etc.
Because the operator appears between the operands, all of these expressions are written in
infix notation.
Prefix Notation
The operator is listed before the operands in the prefix notation. Since the Polish
mathematician invented this system, it is frequently referred to as polish notation.
Example: + A B, -CD etc.
Because the operator occurs before the operands in all of these expressions, prefix notation is
used.
Postfix Notation
The operator is listed after the operands in postfix notation. Polish notation is simply reversed
in this notation, which is also referred to as Reverse Polish notation.
Example: AB +, CD+, etc.
All these expressions are in postfix notation because the operator comes after the operands.
// Abstract Data Type for Stack
abstract class Stack {
public abstract void push(int item);
public abstract int pop();
// Peek the top element without removing it
public abstract int peek();

// Check if the stack is empty


public abstract boolean isEmpty();
}
// Concrete implementation of Stack using an array
class ArrayStack extends Stack {
private static final int MAX_SIZE = 100;
private int[] stack;
private int top;
public ArrayStack() {
stack = new int[MAX_SIZE];
top = -1;
}
@Override
public void push(int item) {
if (top == MAX_SIZE - 1) {
System. out. Println ("Stack is full");
} else {
stack[++top] = item;
}
}
@Override
public int pop() {
if (isEmpty()) {
System.out.println("Stack is empty");
return -1;
} else {
return stack[top--];
}
}
@Override
public int peek() {
if (isEmpty()) {
System.out.println("Stack is empty");
return -1;
} else {
return stack[top];
}
}
@Override
public boolean isEmpty() {
return top == -1;
}
}
// Main class to demonstrate stack operations
public class mainstack {
public static void main(String[] args) {
Stack stack = new ArrayStack();
// Pushing elements onto the stack
stack.push(10);
stack.push(20);
stack.push(30);
// Popping elements from the stack
System.out.println ("Popped: " + stack.pop()); // Output: 30
System.out.println ("Top element: " + stack.peek()); // Output: 20
System.out.println("Is stack empty? " + stack.isEmpty()); // Output: false
}
}

1.LINKED LIST REPRSENTATION OF STACK


// Node class to represent each element in the stack
class Node {
int data; // Data of the node
Node next; // Pointer to the next node
// Constructor to initialize the node with data
public Node(int data) {
this.data = data;
this.next = null;
}
}
// Stack class using LinkedList
public class LinkedListStack {
private Node top; // The top element of the stack
// Constructor to initialize the stack
public LinkedListStack() {
top = null; // Initially, the stack is empty
}
// Check if the stack is empty
public boolean isEmpty() {
return top == null;
}
// Push an element onto the stack
public void push(int value) {
Node newNode = new Node(value);
newNode.next = top; // Point the new node's next to the current top
top = newNode; // Make the new node the top of the stack
System.out.println("Pushed " + value + " onto the stack");
}
// Pop an element from the stack
public int pop() {
if (isEmpty()) {
System.out.println("Stack Underflow! No elements to pop.");
return -1; // Return a sentinel value for underflow
} else {
int poppedValue = top.data; // Get the top element's data
top = top.next; // Move the top pointer to the next node
System.out.println("Popped " + poppedValue + " from the stack");
return poppedValue;
}
}
// Peek at the top element of the stack without removing it
public int peek() {
if (isEmpty()) {
System.out.println("Stack is empty! No elements to peek.");
return -1; // Return a sentinel value for empty stack
} else {
return top.data; // Return the data of the top element
}
}
// Display the elements of the stack
public void display() {
if (isEmpty()) {
System.out.println("Stack is empty.");
} else {
Node current = top; // Start from the top of the stack
System.out.print("Stack elements: ");
while (current != null) {
System.out.print(current.data + " ");
current = current.next; // Move to the next node
}
System.out.println();
}
}
// Main method to test the stack implementation
public static void main(String[] args) {
LinkedListStack stack = new LinkedListStack(); // Create a stack instance
// Push elements onto the stack
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
stack.push(50);
// Display the stack
stack.display();
// Pop elements from the stack
stack.pop();
stack.pop();
// Display the stack after popping
stack.display();
// Peek the top element
System.out.println("Top element is: " + stack. peek());
}
}
1. Node Class:
o A Node represents an individual element in the linked list.
o Each Node has two fields: data (the value of the node) and next (a pointer to the next
node).
2. LinkedListStack Class:
o The top pointer references the top element of the stack.
o Push Operation: When a new value is pushed, a new Node is created, and it becomes
the new top. The next pointer of the new node is set to the previous top.
o Pop Operation: The top node is removed, and the top pointer is moved to the next
node.
o Peek Operation: Returns the data of the top node without modifying the stack.
o Display Operation: Traverses the linked list from the top and prints the stack
elements.
3. Main Method:
o Creates a stack, pushes elements onto it, pops elements from it, and displays the stack
contents after each operation.
o Demonstrates how to peek at the top element and handle cases of an empty stack.
Example Output:
Pushed 10 onto the stack
Pushed 20 onto the stack
Pushed 30 onto the stack
Pushed 40 onto the stack
Pushed 50 onto the stack
Stack elements: 50 40 30 20 10
Popped 50 from the stack
Popped 40 from the stack
Stack elements: 30 20 10
Top element is: 30
CONVERSION OF INFIX TO POSTFIX IN NOTTAION USING STACK
 Input: a * ( b + c + d)
 Output: abc+d+*
 Example 2:
 Input: a*b
 Output: ab*

Algorithm for Conversion of Infix to Postfix using Stack in C

Here are the steps of the algorithm to convert Infix to postfix using stack in C:

 Scan all the symbols one by one from left to right in the given Infix Expression.
 If the reading symbol is an operand, then immediately append it to the Postfix Expression.
 If the reading symbol is left parenthesis ‘( ‘, then Push it onto the Stack.
 If the reading symbol is right parenthesis ‘)’, then Pop all the contents of the stack until the
respective left parenthesis is popped and append each popped symbol to Postfix Expression.
 If the reading symbol is an operator (+, –, *, /), then Push it onto the Stack. However, first,
pop the operators which are already on the stack that have higher or equal precedence than the
current operator and append them to the postfix. If an open parenthesis is there on top of the
stack then push the operator into the stack.
 If the input is over, pop all the remaining symbols from the stack and append them to the
postfix.

Consider the infix expression exp = “a+b*c+d”


and the infix expression is scanned using the iterator i, which is initialized as i = 0.
1st Step: Here i = 0 and exp[i] = ‘a’ i.e., an operand. So add this in the postfix expression. Therefore,
postfix = “a”.

Add ‘a’ in the postfix


2nd Step: Here i = 1 and exp[i] = ‘+’ i.e., an operator. Push this into the stack. postfix = “a” and
stack = {+}.
Push ‘+’ in the stack
3rd Step: Now i = 2 and exp[i] = ‘b’ i.e., an operand. So add this in the postfix expression. postfix =
“ab” and stack = {+}.

Add ‘b’ in the postfix


4th Step: Now i = 3 and exp[i] = ‘*’ i.e., an operator. Push this into the stack. postfix = “ab” and stack
= {+, *}.
Push ‘*’ in the stack
5th Step: Now i = 4 and exp[i] = ‘c’ i.e., an operand. Add this in the postfix expression. postfix =
“abc” and stack = {+, *}.

Add ‘c’ in the postfix


6th Step: Now i = 5 and exp[i] = ‘+’ i.e., an operator. The topmost element of the stack has higher
precedence. So pop until the stack becomes empty or the top element has less precedence. ‘*’ is
popped and added in postfix. So postfix = “abc*” and stack = {+}.
Pop ‘*’ and add in postfix
Now top element is ‘+‘ that also doesn’t have less precedence. Pop it. postfix = “abc*+”.

Pop ‘+’ and add it in postfix


Now stack is empty. So push ‘+’ in the stack. stack = {+}.
Push ‘+’ in the stack
7th Step: Now i = 6 and exp[i] = ‘d’ i.e., an operand. Add this in the postfix expression. postfix =
“abc*+d”.

Add ‘d’ in the postfix


Final Step: Now no element is left. So empty the stack and add it in the postfix expression. postfix =
“abc*+d+”.
QUEUE ADT

II. Queue ADT


A queue is a linear data structure that allows data to be accessed from both ends. There are two main
operations in the queue: push (this operation inserts data to the back of the queue) and pop (this
operation is used to remove data from the front of the queue).
Some of the most essential operations defined in Queue ADT are listed below.
 enqueue() – Insertion of elements to the queue.
 dequeue() – Removal of elements from the queue.
 peek() or front()- Acquires the data element available at the front node of the queue without
deleting it.
 rear() – This operation returns the element at the rear end without removing it.
 isFull() – Validates if the queue is full.
 isEmpty() – Checks if the queue is empty.
 size(): This operation returns the size of the queue i.e. the total number of elements it
contains.

Queue Data Structure


import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {


public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();

// add elements to the queue


queue.add("apple");
queue.add("banana");
queue.add("cherry");

// print the queue


System.out.println("Queue: " + queue);

// remove the element at the front of the queue


String front = queue.remove();
System.out.println("Removed element: " + front);
// print the updated queue
System.out.println("Queue after removal: " + queue);

// add another element to the queue


queue.add("date");

// peek at the element at the front of the queue


String peeked = queue.peek();
System.out.println("Peeked element: " + peeked);

// print the updated queue


System.out.println("Queue after peek: " + queue);
}
}

Output
Queue: [apple, banana, cherry]
Removed element: apple
Queue after removal: [banana, cherry]
Peeked element: banana
Queue after peek: [banana, cherry, date]

III. CIRCULAR QUEUE


// Java program
A Circular Queue is an extended version of a normal queue where the last element of the queue is
connected to the first element of the queue forming a circle.
The operations are performed based on FIFO (First In First Out) principle. It is also called ‘Ring
Buffer’.

In a normal Queue, we can insert elements until queue becomes full. But once queue becomes full, we
can not insert the next element even if there is a space in front of queue.
Operations on Circular Queue:
 Front: Get the front item from the queue.
 Rear: Get the last item from the queue.
 enQueue(value) This function is used to insert an element into the circular queue. In a
circular queue, the new element is always inserted at the rear position.
o Check whether the queue is full – [i.e., the rear end is in just before the front end in a
circular manner].
o If it is full then display Queue is full.
o If the queue is not full then, insert an element at the end of the queue.
 deQueue() This function is used to delete an element from the circular queue. In a circular
queue, the element is always deleted from the front position.
o Check whether the queue is Empty.
o If it is empty then display Queue is empty.
o If the queue is not empty, then get the last element and remove it from the
queue.
Illustration of Circular Queue Operations:
Follow the below image for a better understanding of the enqueue and dequeue operations.

Working of Circular queue operations


How to Implement a Circular Queue?
A circular queue can be implemented using two data structures:
 Array
 Linked List
Here we have shown the implementation of a circular queue using an array data structure.
Implement Circular Queue using Array:
1. Initialize an array queue of size n, where n is the maximum number of elements that the queue
can hold.
2. Initialize two variables front and rear to -1.
3. Enqueue: To enqueue an element x into the queue, do the following:
 Increment rear by 1.
o If rear is equal to n, set rear to 0.
 If front is -1, set front to 0.
 Set queue[rear] to x.
4. Dequeue: To dequeue an element from the queue, do the following:
 Check if the queue is empty by checking if front is -1.
o If it is, return an error message indicating that the queue is empty.
 Set x to queue[front].
 If front is equal to rear, set front and rear to -1.
 Otherwise, increment front by 1 and if front is equal to n, set front to 0.
 Return x.
/ CircularQueue.java
class CircularQueue {
private int[] queue;
private int front, rear, size, capacity;

// Constructor to initialize the queue


public CircularQueue(int capacity) {
this.capacity = capacity;
this.queue = new int[capacity];
this. front = -1;
this. rear = -1;
this. size = 0;
}

// Check if the queue is full


public boolean isFull() {
return size == capacity;
}

// Check if the queue is empty


public boolean isEmpty() {
return size == 0;
}

// Enqueue an element to the queue


public void enqueue(int item) {
if (isFull()) {
System.out.println("Queue is full. Cannot enqueue.");
} else {
if (front == -1) { // If the queue is empty
front = 0;
}
rear = (rear + 1) % capacity; // Circular increment
queue[rear] = item;
size++;
System.out.println("Enqueued: " + item);
}
}

// Dequeue an element from the queue


public int dequeue() {
if (isEmpty()) {
System.out.println("Queue is empty. Cannot dequeue.");
return -1;
} else {
int item = queue[front];
front = (front + 1) % capacity; // Circular increment
size--;
return item;
}
}

// Peek at the front element


public int peek() {
if (isEmpty()) {
System.out.println("Queue is empty.");
return -1;
} else {
return queue[front];
}
}

// Get the current size of the queue


public int getSize() {
return size;
}

// Display the elements in the queue


public void display() {
if (isEmpty()) {
System.out.println("Queue is empty.");
} else {
System.out.println("Queue elements: ");
for (int i = 0; i < size; i++) {
System.out.print(queue[(front + i) % capacity] + " ");
}
System.out.println();
}
}
}

// Main.java
public class Main {
public static void main(String[] args) {
CircularQueue cq = new CircularQueue(5); // Create a queue with capacity of 5

// Test the CircularQueue operations


cq.enqueue(10);
cq.enqueue(20);
cq.enqueue(30);
cq.enqueue(40);
cq.enqueue(50);

cq.display(); // Display the queue

// Attempt to enqueue when the queue is full


cq.enqueue(60);

// Dequeue some elements


System.out.println("Dequeued: " + cq.dequeue());
System.out.println("Dequeued: " + cq.dequeue());

cq.display(); // Display the queue after dequeuing

// Enqueue more elements


cq.enqueue(60);
cq.enqueue(70);

cq.display(); // Display the queue after more enqueues


// Check the size and peek at the front
System.out.println("Size of queue: " + cq.getSize());
System.out.println("Front element: " + cq.peek());
}
}

Output:
Enqueued: 10
Enqueued: 20
Enqueued: 30
Enqueued: 40
Enqueued: 50
Queue elements:
10 20 30 40 50
Queue is full. Cannot enqueue.
Dequeued: 10
Dequeued: 20
Queue elements:
30 40 50
Enqueued: 60
Enqueued: 70
Queue elements:
30 40 50 60 70
Size of queue: 5
Front element: 30

IV. PRIORITY QUEUE


A priority queue is an abstract data type that behaves similarly to the normal queue except that
each element has some priority, i.e., the element with the highest priority would come first in a
priority queue. The priority of the elements in a priority queue will determine the order in which
elements are removed from the priority queue.

The priority queue supports only comparable elements, which means that the elements are either
arranged in an ascending or descending order.

For example, suppose we have some values like 1, 3, 4, 8, 14, 22 inserted in a priority queue with
an ordering imposed on the values is from least to the greatest. Therefore, the 1 number would be
having the highest priority while 22 will be having the lowest priority.

We have a priority queue that contains the following values:

1, 3, 4, 8, 14, 22

All the values are arranged in ascending order. Now, we will observe how the priority queue will
look after performing the following operations:

poll(): This function will remove the highest priority element from the priority queue. In the
above priority queue, the '1' element has the highest priority, so it will be removed from the
priority queue.
5. add(2): This function will insert '2' element in a priority queue. As 2 is the smallest element
among all the numbers so it will obtain the highest priority.

6. poll(): It will remove '2' element from the priority queue as it has the highest priority queue.

7. add(5): It will insert 5 element after 4 as 5 is larger than 4 and lesser than 8, so it will obtain
the third highest priority in a priority queue.

8. Types of Priority Queue

9. There are two types of priority queue:


10. Ascending order priority queue: In ascending order priority queue, a lower priority number
is given as a higher priority in a priority. For example, we take the numbers from 1 to 5
arranged in an ascending order like 1,2,3,4,5; therefore, the smallest number, i.e., 1 is given
as the highest priority in a priority queue.

11. Descending order priority queue: In descending order priority queue, a higher priority
number is given as a higher priority in a priority. For example, we take the numbers from 1 to
5 arranged in descending order like 5, 4, 3, 2, 1; therefore, the largest number, i.e., 5 is given
as the highest priority in a priority queue.

12. Representation of priority queue

13. Now, we will see how to represent the priority queue through a one-way list.
14. Advertisement

15. We will create the priority queue by using the list given below in which INFO list contains
the data elements, PRN list contains the priority numbers of each data element available in
the INFO list, and LINK basically contains the address of the next node.

16.

17. Let's create the priority queue step by step.


18. In the case of priority queue, lower priority number is considered the higher priority,
i.e., lower priority number = higher priority.
A Priority Queue is an abstract data type (ADT) that operates similarly to a queue but with an added
feature: each element in the queue has a priority associated with it. Elements with higher priorities are
dequeued before elements with lower priorities. The priority queue can be implemented using various
data structures, and one common approach is to use a heap.
Heaps and Priority Queues
A heap is a complete binary tree where the value of each node is ordered in a specific way:
 Max Heap: In a Max Heap, the value of each parent node is greater than or equal to the
values of its children. This means the largest element is at the root.
 Min Heap: In a Min Heap, the value of each parent node is less than or equal to the values of
its children. This means the smallest element is at the root.
 A Complete Binary Tree is a type of binary tree in which all levels, except possibly the last,
are completely filled, and all nodes are as far left as possible. It has specific properties that
distinguish it from other types of binary trees.
 Characteristics:
 Node Arrangement:
 All levels, except possibly the last, must be fully filled.
 If the last level is not complete, nodes must be filled from the leftmost side.
 Efficient Storage: A complete binary tree can be efficiently stored in an array since its nodes
follow a specific order.
 Array Representation:
 Root Node: At index 1 (or 0 in zero-based indexing).
 Left Child: At index 2i (or 2i + 1 in zero-based indexing).

 Parent Node: At index ⌊i/2⌋ (or ⌊(i-1)/2⌋ in zero-based indexing).


 Right Child: At index 2i + 1 (or 2i + 2 in zero-based indexing).



A priority queue can be implemented using a Max Heap (for a max-priority queue), where the
highest priority element (the largest value) is at the root.
Operations on Max Heap:
1. Insertion: Add a new element to the heap and restore the heap property (i.e., the max-heap
property).
2. Deletion: Remove the element with the highest priority (the root) and restore the heap
property.
Max Heap Implementation
In this implementation, we will use a Max Heap to implement the priority queue. The heap will be
represented as an array, where the parent-child relationships are determined by the indices of the
array.
 Left child of node at index i: 2 * i + 1
 Right child of node at index i: 2 * i + 2
 Parent of node at index i: (i - 1) / 2
1. Max Heap Class
Here is the implementation of the Max Heap with the insertion and deletion operations:
java
Copy code
class MaxHeap {
private int[] heap;
private int size;
private int capacity;

// Constructor to initialize the heap


public MaxHeap(int capacity) {
this.capacity = capacity;
this.size = 0;
this.heap = new int[capacity];
}

// Helper method to get the index of the left child of a node


private int leftChild(int i) {
return 2 * i + 1;
}

// Helper method to get the index of the right child of a node


private int rightChild(int i) {
return 2 * i + 2;
}

// Helper method to get the index of the parent of a node


private int parent(int i) {
return (i - 1) / 2;
}

// Helper method to swap two elements in the heap


private void swap(int i, int j) {
int temp = heap[i];
heap[i] = heap[j];
heap[j] = temp;
}

// Method to maintain the max-heap property after insertion


private void heapifyUp(int i) {
while (i > 0 && heap[parent(i)] < heap[i]) {
swap(i, parent(i));
i = parent(i);
}
}

// Method to maintain the max-heap property after deletion


private void heapifyDown(int i) {
int left = leftChild(i);
int right = rightChild(i);
int largest = i;
if (left < size && heap[left] > heap[largest]) {
largest = left;
}
if (right < size && heap[right] > heap[largest]) {
largest = right;
}
if (largest != i) {
swap(i, largest);
heapifyDown(largest);
}
}

// Insert a new element into the max-heap


public void insert(int value) {
if (size >= capacity) {
System.out.println("Heap is full. Cannot insert element.");
return;
}
heap[size] = value;
size++;
heapifyUp(size - 1); // Ensure the max-heap property is maintained
}

// Delete the root (max element) from the max-heap


public int deleteMax() {
if (size <= 0) {
System.out.println("Heap is empty. Cannot delete element.");
return Integer.MIN_VALUE;
}

// Root holds the max value


int max = heap[0];

// Replace the root with the last element


heap[0] = heap[size - 1];
size--;
heapifyDown(0); // Restore the max-heap property

return max;
}

// Method to print the heap (for debugging purposes)


public void printHeap() {
for (int i = 0; i < size; i++) {
System.out.print(heap[i] + " ");
}
System.out.println();
}
}

V. ARRAY LIST
The java.util.ArrayList class in Java is part of the Java Collections Framework and provides a
dynamic array that can grow as needed. It is widely used for storing and manipulating lists of objects.
The ArrayList class implements the List interface and allows for efficient random access to elements,
as well as insertion and deletion operations.
Key Features of ArrayList:
1. Dynamic Size: Unlike arrays, which have a fixed size, an ArrayList can grow or shrink as
elements are added or removed.
2. Index-based Access: Elements in an ArrayList can be accessed using an index, similar to
arrays.
3. Resizing: As elements are added, the ArrayList automatically resizes its internal array to
accommodate more elements.
4. Allows Duplicates: Like most List implementations, ArrayList allows duplicate elements.
5. Order is Preserved: The order of elements in an ArrayList is maintained based on the order
in which they were added.
6. Null Values: ArrayList allows the insertion of null values (though this is not recommended in
certain contexts).
Common Methods in ArrayList:
 add(E e): Adds the specified element to the end of the list.
 add(int index, E element): Inserts the specified element at the specified position in the list.
 remove(int index): Removes the element at the specified position in the list.
 remove(Object o): Removes the first occurrence of the specified element from the list.
 get(int index): Returns the element at the specified position in the list.
 set(int index, E element): Replaces the element at the specified position with the specified
element.
 size(): Returns the number of elements in the list.
 isEmpty(): Checks if the list is empty.
 contains(Object o): Returns true if the list contains the specified element.
 clear(): Removes all elements from the list.
Example: Basic Usage of ArrayList
Here's an example demonstrating the creation and basic operations of an ArrayList in Java:
java
Copy code
import java.util.ArrayList;

public class ArrayListExample {


public static void main(String[] args) {
// Create an ArrayList of Integer type
ArrayList<Integer> numbers = new ArrayList<>();

// Add elements to the ArrayList


numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
numbers.add(50);

// Print the ArrayList


System.out.println("ArrayList: " + numbers); // Output: [10, 20, 30, 40, 50]

// Access an element by index


System.out.println("Element at index 2: " + numbers.get(2)); // Output: 30

// Modify an element at a specific index


numbers.set(2, 35); // Change the value at index 2 to 35
System.out.println("Updated ArrayList: " + numbers); // Output: [10, 20, 35, 40, 50]
// Remove an element by index
numbers.remove(3); // Remove the element at index 3 (which is 40)
System.out.println("After removing element at index 3: " + numbers); // Output: [10, 20, 35, 50]

// Remove an element by value


numbers.remove(Integer.valueOf(20)); // Remove the first occurrence of 20
System.out.println("After removing element 20: " + numbers); // Output: [10, 35, 50]

// Check if the list contains an element


System.out.println("Does the list contain 35? " + numbers.contains(35)); // Output: true

// Get the size of the ArrayList


System.out.println("Size of the ArrayList: " + numbers.size()); // Output: 3

// Check if the ArrayList is empty


System.out.println("Is the ArrayList empty? " + numbers.isEmpty()); // Output: false

// Clear all elements from the ArrayList


numbers.clear();
System.out.println("ArrayList after clearing: " + numbers); // Output: []
}
}
Output:
ArrayList: [10, 20, 30, 40, 50]
Element at index 2: 30
Updated ArrayList: [10, 20, 35, 40, 50]
After removing element at index 3: [10, 20, 35, 50]
After removing element 20: [10, 35, 50]
Does the list contain 35? true
Size of the ArrayList: 3
Is the ArrayList empty? false
ArrayList after clearing: []

VI. Vector
The java.util.Vector class in Java is part of the Java Collections Framework and represents a
growable array of objects. It's similar to an ArrayList but with some differences in terms of internal
implementation and behavior. A Vector is a dynamic array that can automatically resize itself when
elements are added or removed.
Key Characteristics of Vector:
1. Resizable Array: A Vector grows dynamically as more elements are added to it. Initially, a
Vector has a default size, and it increases its capacity as needed (usually doubling its size).
2. Thread-Safety: Unlike ArrayList, the methods in Vector are synchronized, which means it is
thread-safe. However, this can lead to performance issues in multi-threaded environments
where thread-safety is not needed.
3. Can hold any type of object: Since Vector is a generic container, it can hold any type of
objects, such as Integer, String, Object, etc.

The size() method gives the number of elements currently in the Vector.
import java.util.Vector;

public class VectorExample {


public static void main(String[] args) {
// Creating a Vector of Strings
Vector<String> vector = new Vector<>();

// Adding elements to the Vector


vector.add("Apple");
vector.add("Banana");
vector.add("Cherry");
vector.add("Date");

// Printing the Vector


System.out.println("Initial Vector: " + vector);

// Accessing elements using get() method


System.out.println("First element: " + vector.get(0)); // Apple
System.out.println("Second element: " + vector.get(1)); // Banana

// Changing an element at a specific index


vector.set(2, "Orange"); // Replacing "Cherry" with "Orange"
System.out.println("After modification: " + vector);

// Removing an element from the Vector


vector.remove("Banana");
System.out.println("After removing 'Banana': " + vector);

// Iterating over the Vector using a for-each loop


System.out.println("Iterating through the Vector:");
for (String fruit : vector) {
System.out.println(fruit);
}

// Checking if the Vector contains a specific element


if (vector.contains("Apple")) {
System.out.println("Vector contains 'Apple'");
} else {
System.out.println("Vector does not contain 'Apple'");
}

// Checking the size of the Vector


System.out.println("Size of the Vector: " + vector.size());
}
}

Sample Output:
Initial Vector: [Apple, Banana, Cherry, Date]
First element: Apple
Second element: Banana
After modification: [Apple, Banana, Orange, Date]
After removing 'Banana': [Apple, Orange, Date]
Iterating through the Vector:
Apple
Orange
Date
Vector contains 'Apple'
Size of the Vector: 3
Key Points:

4. Thread Safety: As mentioned earlier, Vector is synchronized, making it thread-safe


but slower

VII. Java iterators


In Java, iterators are used to traverse through the elements of a collection (such as a list, set, or
queue) in a systematic manner, providing a way to access elements one by one. The java.util.Iterator
interface is part of the Java Collections Framework and allows you to iterate over any collection
that implements the Collection interface, such as ArrayList, HashSet, and LinkedList.
Key Features of Iterator:
 Traversal: Provides a way to traverse the collection sequentially.
 Universal: Works with all types of collections, including lists, sets, and queues.
 Remove Operation: Allows the removal of elements during iteration (in addition to just
traversing).
 Forward-only: By default, an Iterator moves in only one direction — from the first element
to the last element.
Iterator Interface
The Iterator interface defines the following methods:
1. Boolean hasNext(): Returns true if there are more elements in the collection to iterate over.
Otherwise, it returns false.
2. next(): Returns the next element in the iteration and moves the iterator to the next position.
3. remove(): Removes the last element returned by the iterator. This method is optional and can
throw UnsupportedOperationException if the collection does not support removal during
iteration.
Example: Using Iterator with a List
Here's an example of how to use the Iterator with an ArrayList:
java
Copy code
import java.util.ArrayList;
import java.util.Iterator;

public class IteratorExample {


public static void main(String[] args) {
// Create an ArrayList
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
fruits.add("Date");

// Get an iterator for the list


Iterator<String> iterator = fruits.iterator();

// Iterate through the list using hasNext() and next()


System.out.println("Iterating using Iterator:");
while (iterator.hasNext()) {
String fruit = iterator.next();
System.out.println(fruit);
}

// Demonstrating the remove() method


System.out.println("\nRemoving elements while iterating:");
iterator = fruits.iterator(); // Reset the iterator
while (iterator.hasNext()) {
String fruit = iterator.next();
if (fruit.equals("Banana")) {
iterator.remove(); // Remove "Banana" from the list
}
}

// Print the list after removal


System.out.println("List after removal: " + fruits);
}
}
Output:
vbnet
Copy code
Iterating using Iterator:
Apple
Banana
Cherry
Date

Removing elements while iterating:


List after removal: [Apple, Cherry, Date]

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy