Java ArrayDeque Real-World Example

In this source code example, Java ArrayDeque is used as a Stack to manage employee tasks, adhering to the "Last In, First Out" principle in the context of a real-world scenario.

ArrayDeque (Array Double-Ended Queue) is a resizable array implementation of the Deque interface. It is part of the Java Collections Framework and resides in the java.util package.

Employee Task Management with ArrayDeque as Stack

import java.util.ArrayDeque;

class Employee {
    private String name;
    private String task;

    public Employee(String name, String task) {
        this.name = name;
        this.task = task;
    }

    @Override
    public String toString() {
        return name + " assigned: " + task;
    }
}

public class EmployeeManagement {
    public static void main(String[] args) {
        // 1. Initialization
        ArrayDeque<Employee> taskStack = new ArrayDeque<>();
        System.out.println("Initialized task stack: " + taskStack);

        // 2. Assigning tasks
        taskStack.push(new Employee("John", "Write the weekly report"));
        taskStack.push(new Employee("Jane", "Attend client meeting"));
        taskStack.push(new Employee("Bob", "Review code changes"));
        System.out.println("\nAfter assigning tasks:");
        for (Employee e : taskStack) {
            System.out.println(e);
        }

        // 3. Completing tasks
        System.out.println("\n" + taskStack.pop() + " - Task Completed!");
        System.out.println(taskStack.peek() + " - Next Task to Complete!");

        // 4. Status after completing a task
        System.out.println("\nStatus after completing a task:");
        for (Employee e : taskStack) {
            System.out.println(e);
        }
    }
}

Output:

Initialized task stack: []

After assigning tasks:
Bob assigned: Review code changes
Jane assigned: Attend client meeting
John assigned: Write the weekly report

Bob assigned: Review code changes - Task Completed!
Jane assigned: Attend client meeting - Next Task to Complete!

Status after completing a task:
Jane assigned: Attend client meeting
John assigned: Write the weekly report

Explanation:

1. An ArrayDeque of type Employee is initialized to manage tasks. ArrayDeque can be efficiently used as a stack.

2. Tasks are assigned to employees. They are added to the stack with the push operation, so the last task added is on the top.

3. pop() is used to mark the completion of the most recently assigned task.

4. peek() is used to check the next task that needs to be completed without removing it.

5. The status of the task stack is displayed after completing one task.


Comments