Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 43a1c5e

Browse filesBrowse files
committed
Add ArrayListQueue
1 parent d58ea1d commit 43a1c5e
Copy full SHA for 43a1c5e

File tree

Expand file treeCollapse file tree

1 file changed

+78
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+78
-0
lines changed

‎Data Structures/ArrayListQueue.java

Copy file name to clipboard
+78Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
import java.util.ArrayList;
2+
3+
/**
4+
* This class represents the concept of a classical, theoretical Queue. It supports the two basic operations,
5+
* Enqueue and Dequeue, as well, as isEmpty and size.
6+
*
7+
* @param <T> Being a generic class, one can choose which type to fill the queue with.
8+
*/
9+
public class ArrayListQueue<T> {
10+
11+
private final ArrayList<T> queue;
12+
private final int capacity;
13+
14+
ArrayListQueue(int capacity) {
15+
this.queue = new ArrayList<T>(capacity);
16+
this.capacity = capacity;
17+
}
18+
19+
public void enqueue(T element) {
20+
if (this.queue.size() == this.capacity) {
21+
System.err.println("Queue is full");
22+
23+
return;
24+
}
25+
26+
this.queue.add(element);
27+
}
28+
29+
public T dequeue() {
30+
if (this.queue.isEmpty()) {
31+
System.err.println("Queue is empty");
32+
33+
return null;
34+
}
35+
36+
T element = this.queue.get(0);
37+
this.queue.remove(0);
38+
39+
return element;
40+
}
41+
42+
public boolean isEmpty() {
43+
return this.queue.isEmpty();
44+
}
45+
46+
public int size() {
47+
return this.queue.size();
48+
}
49+
}
50+
51+
class ArrayListQueueExample {
52+
public static void main(String[] args) {
53+
ArrayListQueue<Integer> intQueue = new ArrayListQueue<Integer>(10);
54+
55+
//Fills queue to capacity
56+
for(int i = 0; i < 10; i++) {
57+
intQueue.enqueue(i);
58+
}
59+
60+
//Should print an error
61+
intQueue.enqueue(-1);
62+
63+
//Flushes the queue completely
64+
for(int i = 0; i < 10; i++) {
65+
int element = intQueue.dequeue();
66+
67+
System.out.println(element);
68+
}
69+
70+
//Should print an error and return null
71+
if (intQueue.dequeue() == null) {
72+
//Should be true
73+
System.out.println(intQueue.isEmpty());
74+
}
75+
76+
77+
}
78+
}

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.