In this tutorial, we will discuss how to use the ArrayDeque class.
The ArrayDeque class is basically an Array Double Ended Queue, which supports the insertion and deletion of elements at both ends.
This implementation can be used as a Stack as well as a Queue.
Hierarchy of ArrayDeque class
The ArrayDeque class inherits AbstractCollection class and it implements Deque , Cloneable, Serializable interfaces.
Source code of Item.java
package com.t4b.test;
public class Item {
String name;
int id;
double price;
public Item(String name, int id, double price) {
super();
this.name = name;
this.id = id;
this.price = price;
}
@Override
public String toString() {
return "Item [name=" + name + ", id=" + id + ", price=" + price + "]";
}
}
Source code of TestMain.java
package com.t4b.test;
import java.util.ArrayDeque;
import java.util.Iterator;
public class TestMain {
public static void main(String[] args) {
ArrayDeque<Item> arrdequeue = new ArrayDeque<Item>();
arrdequeue.add(new Item("Apple", 1, 150.0));
arrdequeue.add(new Item("Grape", 2, 250.0));
arrdequeue.addFirst(new Item("Mango", 3, 10));
arrdequeue.addLast(new Item("Pine Apple", 4, 100));
Iterator<Item> itr = arrdequeue.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
// elements can be accessed from both end
System.out.println(arrdequeue.getFirst());
System.out.println(arrdequeue.getLast());
// duplicate elements can be stored
arrdequeue.add(new Item("Grape", 2, 250.0));
itr = arrdequeue.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
// deletion can be performed at both end
System.out.println(arrdequeue.removeFirst());
System.out.println(arrdequeue.removeLast());
}
}

No comments:
Post a Comment
Note: Only a member of this blog may post a comment.