-
Notifications
You must be signed in to change notification settings - Fork 164
/
Copy pathArrayListQueue.java
78 lines (58 loc) · 1.78 KB
/
ArrayListQueue.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import java.util.ArrayList;
/**
* This class represents the concept of a classical, theoretical Queue. It supports the two basic operations,
* Enqueue and Dequeue, as well, as isEmpty and size.
*
* @param <T> Being a generic class, one can choose which type to fill the queue with.
*/
public class ArrayListQueue<T> {
private final ArrayList<T> queue;
private final int capacity;
ArrayListQueue(int capacity) {
this.queue = new ArrayList<T>(capacity);
this.capacity = capacity;
}
public void enqueue(T element) {
if (this.queue.size() == this.capacity) {
System.err.println("Queue is full");
return;
}
this.queue.add(element);
}
public T dequeue() {
if (this.queue.isEmpty()) {
System.err.println("Queue is empty");
return null;
}
T element = this.queue.get(0);
this.queue.remove(0);
return element;
}
public boolean isEmpty() {
return this.queue.isEmpty();
}
public int size() {
return this.queue.size();
}
}
class ArrayListQueueExample {
public static void main(String[] args) {
ArrayListQueue<Integer> intQueue = new ArrayListQueue<Integer>(10);
//Fills queue to capacity
for(int i = 0; i < 10; i++) {
intQueue.enqueue(i);
}
//Should print an error
intQueue.enqueue(-1);
//Flushes the queue completely
for(int i = 0; i < 10; i++) {
int element = intQueue.dequeue();
System.out.println(element);
}
//Should print an error and return null
if (intQueue.dequeue() == null) {
//Should be true
System.out.println(intQueue.isEmpty());
}
}
}