Skill Week - 6 (Java Generics, List, Queue - 27-01-2025 To 01-02-2025)
Skill Week - 6 (Java Generics, List, Queue - 27-01-2025 To 01-02-2025)
Roll no:2300032694
Week 5. Collection Framework Java Generics, List & Queue
Objective: Create a data structure that combines the features of both List and Queue
and focus on balancing the operations and ensuring efficient performance for both
random access and queue operations.
Details:
a) Class Design: Implement a class ListQueue<T> that combines both List and
Queue functionalities.
b) Operations:
✓ add(T element): Adds an element to the end of the queue (similar to
enqueue in a Queue).
✓ remove(): Removes and returns the element from the front of the queue
(similar to dequeue in a Queue).
✓ get(int index): Retrieves the element at the specified index (similar to get
in a List).
✓ set(int index, T element): Replaces the element at the specified index
(similar to set in a List).
c) Internal Storage: Use an internal List<T> to manage elements. Implement
logic to support both Queue and List operations.
Answer
package week6skill;
//Skill Week 6 First Question
import java.util.ArrayList;
Objective: Create a priority queue that orders elements based on their priority and
ensure correct element ordering.
Details:
a) Class Design: Implement a generic class PriorityQueue<T> where T must
implement Comparable<T>.
b) Operations:
✓ enqueue(T element): Adds an element to the queue, maintaining the
order based on the natural ordering of T.
✓ dequeue(): Removes and returns the highest-priority element (the
smallest element according to its Comparable implementation). If the
queue is empty, throw a NoSuchElementException.
✓ peek(): Returns the highest-priority element without removing it. If the
queue is empty, throw a NoSuchElementException.
c) Internal Storage: Use a List<T> to store elements. Maintain the order by
sorting the list or using a priority queue mechanism.
Answer
package HashSet;
import java.util.*;
public class PriorityQueueDemo
{
PriorityQueue<Integer> pq = new PriorityQueue<>();
// Add elements to the queue
void enqueue()
{
pq.add(10);
pq.add(20);
pq.add(30);
pq.add(40);
System.out.println("PriorityQueue: " + pq);
}
void dequeue()
{
// Remove and print elements in priority order
System.out.print("Elements in priority order: ");
System.out.print(pq.peek() + " ");
}
public static void main(String args[])
{
PriorityQueueDemo m=new PriorityQueueDemo();
m.enqueue();
m.dequeue();
}
}