Java deque implementation

Deque Queue

Double-ended queue is an abstract data type. A deque represents a linear collection of elements that support insertion, retrieval and removal of elements at both ends. Dequeue, often abbreviated to deque.

This general data class has some possible sub-types:

  • input-restricted deque: It is one where deletion can be made from both ends, but insertion can be made at one end only.
  • output-restricted deque: It is one where insertion can be made at both ends, but deletion can be made from one end only.

Example

package com.w3schools;
 
import java.util.ArrayList;
import java.util.List;
 
public class Test {
    private List<Integer> deque = new ArrayList<Integer>();
 
    public void insertFront(int item){
        System.out.println("Adding element at front: "+item);
        deque.add(0,item);
        System.out.println(deque);
    }
 
    public void insertRear(int item){
        System.out.println("Adding element at rear: "+item);
        deque.add(item);
        System.out.println(deque);
    }
 
    public void removeFront(){
        if(deque.isEmpty()){
            System.out.println("Underflow state.");
            return;
        }
        int rem = deque.remove(0);
        System.out.println("Remove element from front: "+rem);
        System.out.println(deque);
    }
 
    public void removeRear(){
        if(deque.isEmpty()){
            System.out.println("Underflow state.");
            return;
        }
        int rem = deque.remove(deque.size()-1);
        System.out.println("Removed element from front: "+rem);
        System.out.println(deque);
    }
 
    public int peakFront(){
        int item = deque.get(0);
        System.out.println("Element at first: "+item);
        return item;
    }
 
    public int peakRear(){
        int item = deque.get(deque.size()-1);
        System.out.println("Element at rear: "+item);
        return item;
    }
 
	public static void main(String args[]){
		try {
			Test deque = new Test();
			deque.insertFront(134);
			deque.insertFront(14);
			deque.insertFront(13);
			deque.removeFront();
			deque.insertRear(455);
			deque.removeFront();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Output

Adding element at front: 134
[134]
Adding element at front: 14
[14, 134]
Adding element at front: 13
[13, 14, 134]
Remove element from front: 13
[14, 134]
Adding element at rear: 455
[14, 134, 455]
Remove element from front: 14
[134, 455]