Java Reference
In-Depth Information
The decision to use a generic data type in the declaration of the array
bag
affects how we allo-
cate this array within the constructor. A statement such as
bag =
new
T[capacity];
// SYNTAX ERROR
is syntactically incorrect. You cannot use a generic type when allocating an array. Instead, we allo-
cate an array of objects of type
Object
, as follows:
new
Object[capacity];
However, problems arise when we try to assign this array to the data field
bag
. The statement
bag =
new
Object[capacity];
// SYNTAX ERROR: incompatible types
causes a syntax error because you cannot assign an array of type
Object[]
to an array of type
T[]
.
That is, the types of the two arrays are not compatible.
A cast is necessary but creates its own problem. The statement
bag = (T[])
new
Object[capacity];
produces the compiler warning
ArrayBag.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
If you compile the class again and use the option
-Xlint
, the messages will be more detailed,
beginning as follows:
ArrayBag.java:24: warning: [unchecked] unchecked cast
found : java.lang.Object[]
required: T[]
bag = (T[])new Object[capacity];
^
The compiler wants you to ensure that casting each entry in the array from type
Object
to the
generic type
T
is safe. Since the array has just been allocated, it contains
null
entries. Thus, the cast
is safe, and so we instruct the compiler to ignore the warning by writing the annotation
@SuppressWarnings("unchecked")
before the offending statement. This instruction to the compiler can only precede a method defini-
tion or a variable declaration. Since the assignment
bag = (T[])
new
Object[capacity];
does not declare
bag
—
bag
has already been declared—we revise it as follows:
// the cast is safe because the new array contains null entries
@SuppressWarnings("unchecked")
T[] tempBag = (T[])
new
Object[capacity];
// unchecked cast
bag = tempBag;
Note:
Suppressing compiler warnings
To suppress an unchecked-cast warning from the compiler, you precede the flagged state-
ments with the instruction
@SuppressWarnings("unchecked")
Note that this instruction can precede only a method definition or a variable declaration.
2.8
The constructors.
The following constructor performs the previous steps, using a capacity given
as an argument:
/** Creates an empty bag having a given capacity.
@param capacity the integer capacity desired */