Home > AI > Language > Java > ArrayQueue >

ArrayDequeue

Example :

import java.util.*;

public class Test {
    public static void main(String[] args) {
        // Initializing an deque
        Deque<Integer> q = new ArrayDeque<>(10);

        // add() method to insert
        q.add(10);
        q.add(20);
        q.add(30);
        q.add(40);
        q.add(50);
        for (Integer element : q)
        {
            System.out.println("Element : " + element);
        }

        System.out.println("Using clear() ");

        // clear() method
        q.clear();

        // addFirst() method to insert at start
        q.addFirst(564);
        q.addFirst(291);

        // addLast() method to insert at end
        q.addLast(24);
        q.addLast(14);

        System.out.println("Above elements are removed now");

        // Iterator() :
        System.out.println("Elements of deque using Iterator :");
        for(Iterator itr = q.iterator(); itr.hasNext();)
        {
            System.out.println(itr.next());
        }

        // descendingIterator() : to reverse the deque order
        System.out.println("Elements of deque in reverse order :");
        for(Iterator dItr = q.descendingIterator();
            dItr.hasNext();)
        {
            System.out.println(dItr.next());
        }

        // element() method : to get Head element
        System.out.println("\nHead Element using element(): " +
                q.element());

        // getFirst() method : to get Head element
        System.out.println("Head Element using getFirst(): " +
                q.getFirst());

        // getLast() method : to get last element
        System.out.println("Last Element using getLast(): " +
                q.getLast());

        // toArray() method :
        Object[] arr = q.toArray();
        System.out.println("\nArray Size : " + arr.length);

        System.out.print("Array elements : ");
        for(int i=0; i<arr.length ; i++)
            System.out.print(" " + arr[i]);

        // peek() method : to get head
        System.out.println("\nHead element : " + q.peek());

        // poll() method : to get head
        System.out.println("Head element poll : " + q.poll());

        // push() method :
        q.push(265);
        q.push(984);
        q.push(2365);

        // remove() method : to get head
        System.out.println("Head element remove : " + q.remove());

        System.out.println("The final array is: "+q);
    }
}

Related posts:

Leave a Reply