Java Reference
In-Depth Information
GenericQueue<E>
-list: java.util.LinkedList<E>
+enqueue(e: E): void
+dequeue(): E
+getSize(): int
Adds an element to this queue.
Removes an element from this queue.
Returns the number of elements in this queue.
F
IGURE
24.22
GenericQueue
uses a linked list to provide a first-in, first-out data structure.
L
ISTING
24.7
GenericQueue.java
1
public class
GenericQueue<E> {
2
private
java.util.LinkedList<E> list
linked list
3
=
new
java.util.LinkedList<>();
4
5
public void
enqueue(E e) {
6 list.addLast(e);
7 }
8
9
enqueue
public
E dequeue() {
dequeue
10
return
list.removeFirst();
11 }
12
13
public int
getSize() {
getSize
14
return
list.size();
15 }
16
17 @Override
18
public
String toString() {
toString
19
return
"Queue: "
+ list.toString();
20 }
21 }
A linked list is created to store the elements in a queue (lines 2-3). The
enqueue(e)
method (lines 5-7) adds element
e
into the tail of the queue. The
dequeue()
method (lines
9-11) removes an element from the head of the queue and returns the removed element. The
getSize()
method (lines 13-15) returns the number of elements in the queue.
Listing 24.8 gives an example that creates a stack using
GenericStack
and a queue using
GenericQueue
. It uses the
push
(
enqueue
) method to add strings to the stack (queue) and
the
pop
(
dequeue
) method to remove strings from the stack (queue).
L
ISTING
24.8
TestStackQueue.java
1
public class
TestStackQueue {
2
public static void
main(String[] args) {
3
// Create a stack
4
GenericStack<String> stack =
5
new
GenericStack<>();
6
7
// Add elements to the stack
8 stack.push(
"Tom"
);
// Push it to the stack
9 System.out.println(
"(1) "
+ stack);
10
11 stack.push(
"Susan"
);
// Push it to the the stack
12 System.out.println(
"(2) "
+ stack);
13
14 stack.push(
"Kim"
);
// Push it to the stack
15 stack.push(
"Michael"
);
// Push it to the stack
16 System.out.println(
"(3) "
+ stack);
17
Search WWH ::
Custom Search