bhylu.com

Advertisements

Java Use a Deque for Work at Both Ends

A deque supports adding and removing at either end of a sequence. Express a queue or stack through those operations rather than using random indexes everywhere.

Understand the idea

LinkedList implements List and Deque, but frequent indexed traversal can be costly because reaching a position requires following links. ArrayDeque is often suitable for a non-concurrent queue or stack without null elements. Choose throwing operations such as removeFirst when emptiness is a programming error, or a polling operation when an empty result is expected and handled.

Run it locally

Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.

JDK and terminal setup

javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out Main

A worked example

Java 21+ · Main.java

import java.util.Deque;
import java.util.ArrayDeque;

public class Main {
    public static void main(String[] args) {
        Deque<String> waiting = new ArrayDeque<>();
        waiting.addLast("Leena");
        waiting.addLast("Dev");
        waiting.addFirst("Priority");
        System.out.println(waiting.removeFirst());
        System.out.println(waiting.pollLast());
        System.out.println(waiting);
    }
}

Expected output

Priority
Dev
[Leena]

The priority entry is placed at the front and is served first. pollLast then removes the newest ordinary entry from the other end. This sequence demonstrates operations rather than a claim that prioritisation is fair; a real scheduler needs an explicit fairness policy. Neither ArrayDeque nor LinkedList is automatically safe for concurrent mutation.

Check the official Java documentation for detailed contracts and supported options.