-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy path9. Queues
More file actions
68 lines (46 loc) · 2.15 KB
/
9. Queues
File metadata and controls
68 lines (46 loc) · 2.15 KB
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
import java.util.NoSuchElementException;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
public class App {
public static void main(String[] args) {
// (head) <- oooooooooooooooooooooooo <- (tail) FIFO (first in, first out)
Queue<Integer> q1 = new ArrayBlockingQueue<Integer>(3);
// Throws NoSuchElement exception --- no items in queue yet
// System.out.println("Head of queue is: " + q1.element());
q1.add(10);
q1.add(20);
q1.add(30);
System.out.println("Head of queue is: " + q1.element());
try {
q1.add(40);
} catch (IllegalStateException e) {
System.out.println("Tried to add too many items to the queue.");
}
for(Integer value: q1) {
System.out.println("Queue value: " + value);
}
System.out.println("Removed from queue: " + q1.remove());
System.out.println("Removed from queue: " + q1.remove());
System.out.println("Removed from queue: " + q1.remove());
try {
System.out.println("Removed from queue: " + q1.remove());
} catch (NoSuchElementException e) {
System.out.println("Tried to remove too many items from queue");
}
////////////////////////////////////////////////////////////////////
Queue<Integer> q2 = new ArrayBlockingQueue<Integer>(2);
System.out.println("Queue 2 peek: " + q2.peek());
q2.offer(10);
q2.offer(20);
System.out.println("Queue 2 peek: " + q2.peek());
if(q2.offer(30) == false) {
System.out.println("Offer failed to add third item.");
}
for(Integer value: q2) {
System.out.println("Queue 2 value: " + value);
}
System.out.println("Queue 2 poll: " + q2.poll());
System.out.println("Queue 2 poll: " + q2.poll());
System.out.println("Queue 2 poll: " + q2.poll());
}
}