Java Reference
In-Depth Information
System.out.println("Empty: "+queue.isEmpty());
System.out.println("Full: "+queue.isFull());
}
}
class QueueEmptyException extends Exception
{
}
class QueueFullException extends Exception
{
}
ception
classes. The latter two classes describe checked exceptions that are thrown
from methods of the former class.
Queue
implementsa
queue
,adatastructurethatstoreselementsinfirst-in,first-out
order. An element is inserted at the
tail
and removed at the
head
. The queue is empty
whentheheadequalsthetail,andfullwhenthetailisonelessthanthehead.Asaresult,
a queue of size
n
can store a maximum of
n
-1 elements.
Notice that
Queue<E>
's
E
type parameter appears throughout the source code. For
example,
E
appears in the
elements
array declaration to denote the array's element
type.
E
isalsospecifiedasthetypeof
insert()
'sparameterandas
remove()
'sre-
turn type.
E
alsoappearsin
elements = (E[]) new Object[size];
.(Iwillexplain
laterwhyIspecifiedthisexpressioninsteadofspecifyingthemorecompact
elements
= new E[size];
expression.)
The
E[]
cast results in the compiler warning about this cast being unchecked. The
compilerisconcernedthatdowncastingfrom
Object[]
to
E[]
mightresultinaviol-
ation of type safety because any kind of object can be stored in
Object[]
.
The compiler's concern is not justified in this example. There is no way that a
on-
E
object can appear in the
E[]
array. Because the warning is meaningless in
this context, it is suppressed by prefixing the constructor with
@SuppressWarn-
ings("unchecked")
.
Caution
Becarefulwhensuppressinganuncheckedwarning.Youmustfirstprove
thata
ClassCastException
cannotoccur,andthenyoucansuppressthewarning.
When you run this application, it generates the following output: