0% found this document useful (0 votes)
5 views4 pages

Java Task Scheduler and Jagged Array

The document describes a Java lab practice involving two main tasks: creating a Task class that implements the Comparable interface for priority management and a TaskScheduler class to manage tasks in a priority queue. Additionally, it outlines the creation of a jagged array to store student scores for varying subjects. The provided code demonstrates the implementation of these tasks and their expected outputs.
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)
5 views4 pages

Java Task Scheduler and Jagged Array

The document describes a Java lab practice involving two main tasks: creating a Task class that implements the Comparable interface for priority management and a TaskScheduler class to manage tasks in a priority queue. Additionally, it outlines the creation of a jagged array to store student scores for varying subjects. The provided code demonstrates the implementation of these tasks and their expected outputs.
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

JAVA LAB PRACTICE(COLLECTION)

Q1. Define a simple class named Task with the following fields:

 id (an integer)

 name (a String)

 priority (an integer, where 1 is the highest priority and higher numbers are lower
priority).
The Task class must implement the Comparable interface to define the natural
ordering (priority) for the PriorityQueue.
Step 2: Implement the Comparable Interface
Implement the compareTo(Task other) method in the Task class. This method must
ensure that:

 The task with the lower priority number is considered "smaller" and therefore gets
the highest priority in the queue.
Step 3: Create the TaskScheduler Class
Define a class named TaskScheduler with the following methods:
addTask(Task task): Adds a new task to the queue.
getNextTask(): Retrieves and removes the task with the highest priority. If the queue
is empty, it should return null.
peekNextTask(): Retrieves but does not remove the task with the highest priority. If
the queue is empty, it should return null.
Step 4: Write a Main Method for Testing
In your main method:
Create an instance of TaskScheduler.
Add a mix of tasks with different priorities (e.g., Task A: P3, Task B: P1, Task C: P2).
Demonstrate retrieving and processing tasks, showing that they are handled in the
correct priority order.

SOL: package LabPracticeCollection;


import [Link];
class Task implements Comparable<Task> {
int id;
String name;
int priority;
public Task(int id, String name, int priority) {
[Link] = id;
[Link] = name;
[Link] = priority;
}
@Override
public int compareTo(Task other) {
return [Link]([Link], [Link]);
}
@Override
public String toString() {
return "Task{id=" + id + ", name='" + name + "', priority=" + priority + '}';
}
}
class TaskScheduler {

private PriorityQueue<Task> taskQueue;


public TaskScheduler() {
taskQueue = new PriorityQueue<>();
}
public void addTask(Task task) {
[Link](task);
}
public Task getNextTask() {
return [Link]();
}
public Task peekNextTask() {
return [Link]();
}
}
public class que1 {
public static void main(String[] args) {
TaskScheduler scheduler = new TaskScheduler();
[Link](new Task(1, "Task A", 3));
[Link](new Task(2, "Task B", 1));
[Link](new Task(3, "Task C", 2));
[Link]("Next Task (peek): " + [Link]());
[Link]("Processing Task: " + [Link]());
[Link]("Processing Task: " + [Link]());
[Link]("Processing Task: " + [Link]());
[Link]("Next Task (peek): " + [Link]());
}
}

OUTPUT: Next Task (peek): Task{id=2, name='Task B', priority=1}

Processing Task: Task{id=2, name='Task B', priority=1}

Processing Task: Task{id=3, name='Task C', priority=2}

Processing Task: Task{id=1, name='Task A', priority=3}

Next Task (peek): null


Q2. Step1: Declare and Initialize the Jagged Array

Declare a two-dimensional integer array named student Scores.


Initialize this array to store data for three students.
The number of subjects (columns) for each student should be different (jagged):

 Student 0: Has scores for 4 subjects.

 Student 1: Has scores for 2 subjects.

 Student 2: Has scores for 5 subjects.


Step 2: Populate the Array

Populate the student Scores array with sample test scores (integers) for each student
and subject.

0
$85, 90, 78, 92$
1
$65, 70$
2
$95, 88, 91, 100, 80$

SOL: package LabPracticeCollection;


public class que2 {
public static void main(String[] args) {
int[][] studentScores = new int[3][];
studentScores[0] = new int[4];
studentScores[1] = new int[2];
studentScores[2] = new int[5];
studentScores[0] = new int[] {85, 90, 78, 92};
studentScores[1] = new int[] {65, 70};
studentScores[2] = new int[] {95, 88, 91, 100, 80};
for (int i = 0; i < [Link]; i++) {
[Link]("Student " + i + ": ");
for (int j = 0; j < studentScores[i].length; j++) {
[Link](studentScores[i][j] + " ");
}
[Link]();
}
}
}
OUTPUT: Student 0: 85 90 78 92

Student 1: 65 70

Student 2: 95 88 91 100 80

Common questions

Powered by AI

Benefits of using a PriorityQueue include efficient retrieval of the highest priority task due to its logarithmic time complexity for both insertion and removal. This makes it suitable for simple task scheduling scenarios where priorities are well-defined and static. Limitations include the lack of built-in support for dynamic priority changes and the inability to efficiently search for specific tasks, as PriorityQueue is inherently unsorted .

Using a Comparator provides flexibility in defining multiple ordering schemes for a class without altering the class itself, unlike Comparable's single natural ordering. This allows different priority rules based on context without modifying the Task class, facilitating scenarios where tasks might be prioritized differently under varied circumstances .

In the TaskScheduler class, tasks are added to the queue using the addTask method which inserts tasks into the PriorityQueue. Tasks are retrieved using getNextTask, which removes and returns the task with the highest priority. If the queue is empty, getNextTask returns null. The peekNextTask method can be used to look at the highest priority task without removing it, returning null if the queue is empty .

To handle dynamic priority changes, one could implement a wrapper around the PriorityQueue that supports updating priority by removing a task, changing its priority, and re-inserting it into the queue. Alternatively, using a balanced tree structure or a custom heap implementation that supports priority updates directly might be more efficient .

Setting up a jagged array involves first declaring a two-dimensional array with an unspecified number of columns, then initializing each sub-array independently with its desired size. In the provided example, each student in the studentScores array is assigned scores for a varying number of subjects by creating and populating sub-arrays with different lengths .

Real-world data variability can be translated through structures like jagged arrays, which handle datasets where the size is inconsistent across different records. For example, in educational databases where students have taken different numbers of electives, a jagged array allows each student's subject list to dynamically conform to actual data, optimizing memory usage and access efficiency .

Verification can be done by creating test cases that add tasks in unsorted priority order and subsequently retrieving tasks using getNextTask to ensure they are processed in the correct priority order. By printing the outcome of each retrieval, as shown in the provided main method, you can confirm whether tasks are handled by their priority numbers, validating its effectiveness .

A jagged array in Java is an array of arrays where each sub-array can have a different length, unlike a regular two-dimensional array where each row has the same number of columns. This structure is useful in scenarios where the dataset varies in size, such as storing test scores where each student may have taken a different number of subjects. This is distinctly demonstrated in the studentScores jagged array example .

Key considerations include managing memory effectively as jagged arrays may lead to increased complexity in accessing and iterating over elements due to varying sub-array lengths. It’s important to handle potential null pointer exceptions by ensuring all sub-arrays are initialized before use. Moreover, understanding the specific use case, like varying data sizes, is essential to leverage jagged arrays efficiently .

The Task class implements the Comparable interface, providing a compareTo method that orders tasks based on their priority values. A lower integer value for priority indicates a higher priority, thereby ensuring that a task with a lower priority number is considered "smaller" and is processed earlier in a PriorityQueue .

You might also like