Java Collection: ArrayDeque - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

demo-image

Java Collection: ArrayDeque

Share This

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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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 + "]";
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Source code of TestMain.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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());
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Happy Exploring!

Comment Using!!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.