-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueueClass.java
More file actions
52 lines (39 loc) · 1.64 KB
/
Copy pathQueueClass.java
File metadata and controls
52 lines (39 loc) · 1.64 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
package java8;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.Queue;
public class QueueClass {
public static void main(String[] args) {
Queue<String> myQueue = new LinkedList();
// add elements in the queue using offer() - return true/false
myQueue.offer("Monday");
myQueue.offer("Thusday");
boolean flag = myQueue.offer("Wednesday");
System.out.println("Wednesday inserted successfully? "+flag);
// add more elements using add() - throws IllegalStateException
try {
myQueue.add("Thursday");
myQueue.add("Friday");
myQueue.add("Weekend");
} catch (IllegalStateException e) {
e.printStackTrace();
}
System.out.println("Pick the head of the queue: " + myQueue.peek());
String head = null;
try {
// remove head - remove()
head = myQueue.remove();
System.out.print("1) Push out " + head + " from the queue ");
System.out.println("and the new head is now: "+myQueue.element());
} catch (NoSuchElementException e) {
e.printStackTrace();
}
// remove the head - poll()
head = myQueue.poll();
System.out.print("2) Push out " + head + " from the queue");
System.out.println("and the new head is now: "+myQueue.peek());
// find out if the queue contains an object
System.out.println("Does the queue contain 'Weekend'? " + myQueue.contains("Weekend"));
System.out.println("Does the queue contain 'Monday'? " + myQueue.contains("Monday"));
}
}