Quick and dirty demonstration of Java Queue class behavior.
Notes:
If the case of the queue being empty is "usual" or "normal," likely it's best to use peek() and poll(). Otherwise, if the queue should never be empty, choose the other two.
01.
package
com.etretatlogiciels.queue;
02.
03.
import
java.util.Queue;
04.
import
java.util.LinkedList;
05.
06.
public
class
DemoQueue
07.
{
08.
static
void
println( String string )
09.
{
10.
if
( string ==
null
)
11.
System.out.println();
12.
else
13.
System.out.println( string );
14.
}
15.
16.
public
static
void
main( String[] args )
17.
{
18.
System.out.println(
"Queue in Java"
);
19.
System.out.println(
"-----------------------"
);
20.
21.
println(
" You cannot create an instance of Queue as it's abstract,"
);
22.
println(
" so you create an instance of LinkedList and assign it to"
);
23.
println(
" a Queue object."
);
24.
Queue< String > queue =
new
LinkedList< String >();
25.
26.
println(
null
);
27.
println(
" Add elements to queue..."
);
28.
queue.add(
"Java"
);
29.
queue.add(
"Python"
);
30.
31.
queue.add(
"JavaScript"
);
32.
queue.add(
"HTML 5"
);
33.
queue.add(
"Hadoop"
);
34.
35.
println(
null
);
36.
println(
" Items in the queue: "
+ queue );
37.
println(
null
);
38.
39.
println(
" Remove the first element from the queue, here Java:"
);
40.
println(
" +------+"
);
41.
println(
" remove(): | "
+ queue.remove() +
" |"
);
42.
println(
" +------+"
);
43.
44.
println(
" Retrieve the next/topmost element in the queue, as Java is gone, Python:"
);
45.
println(
" +--------+"
);
46.
println(
" element(): | "
+ queue.element() +
" |"
);
47.
println(
" +--------+"
);
48.
49.
println(
" Retrieve AND remove the next/topmost element of the queue, still Python:"
);
50.
println(
" +--------+"
);
51.
println(
" poll(): | "
+ queue.poll() +
" |"
);
52.
println(
" +--------+"
);
53.
54.
println(
" Peek at the current, topmost element in the queue to peek at it, JavaScript:"
);
55.
println(
" +------------+"
);
56.
println(
" peek(): | "
+ queue.peek() +
" |"
);
57.
println(
" +------------+"
);
58.
}
59.
}
Output:
Queue in Java ----------------------- You cannot create an instance of Queue as it's abstract, so you create an instance of LinkedList and assign it to a Queue object. Add elements to queue... Items in the queue: [Java, Python, JavaScript, HTML 5, Hadoop] Remove the first element from the queue, here Java: +------+ remove(): | Java | +------+ Retrieve the next/topmost element in the queue, as Java is gone, Python: +--------+ element(): | Python | +--------+ Retrieve AND remove the next/topmost element of the queue, still Python: +--------+ poll(): | Python | +--------+ Peek at the current, topmost element in the queue to peek at it, JavaScript: +------------+ peek(): | JavaScript | +------------+