Menu
Topics Index
...
`

DequeDemo - Java Example Program


DequeDemo
class DequeDemo
{
    Deque dq = new ArrayDeque<String>();
    dq.add("C++");
    dq.add("C#");
    dq.add("Java");
    System.out.println("Till now elements in dequeu : " + dq);
    // C added to first
    dq.addFirst("C"); // LINE A
    System.out.println("deque after adding C at first: " + dq);
    // Now FORTRAN is added first
    dq.addFirst("FORTRAN"); // LINE B
    System.out.println("deque after  adding FORTRAN at first : " + dq);
    // Now removing from deque
    //Removing Java from deque
    dq.remove("Java"); // LINE C
    System.out.println("deque after removing Java : " + dq);
    //Removing FirstElement
    dq.removeFirst(); // LINE D
    System.out.println("deque after removing first element : " + dq);
    dq.removeLast(); // LINE E
    System.out.println("deque after removing last element : " + dq);
}
OUTPUT

Till now elements in dequeu : [C++, C#, Java]
deque after adding C at first: [C, C++, C#, Java]
deque after  adding FORTRAN at first : [FORTRAN, C, C++, C#, Java]
deque after removing Java : [FORTRAN, C, C++, C#]
deque after removing first element : [C, C++, C#]
deque after removing last element : [C, C++]

DESCRIPTION

In the above program we have created a deque and added elements to it. At LINE A we added C to the first of deque. At LINE B we added FORTRAN to the first of deque At LINE C we removed Java from deque. At LINE D we have removed first element in the deque. At LINE E we have removed last element from deque.

THINGS TO TRY
  • Add SQL to the first of deque and Ruby to the last of deque using offerFirst and offerLast methods and print the deque.
    dq.offerFirst("SQL");
    dq.offerLast("Ruby");
    System.out.println(dq);
  • Remove first element from deque and print deque
    System.out.println("Removed first element from deque : " + dq.pop() + "\n" + dq);
  • Check whether Pearl is in deque
    System.out.println("deque contains Pearl : " + dq.contains("Pearl"));

© meritcampus 2019

All Rights Reserved.

Open In App