Java Reference
In-Depth Information
When the class is compiled, it emits an unchecked cast warning:
Click here to view code image
// Unchecked cast warning
ArrayList.java:305: warning: [unchecked] unchecked cast found :
Object[], required: T[]
return (T[]) Arrays.copyOf(elements, size, a.getClass());
This warning cannot be suppressed for just the return statement because it is not a
declaration [JLS 2013]. As a result, the programmer suppresses warnings for the entire
method. This can cause issues when functionality that performs type-unsafe operations is
added to the method at a later date [Bloch 2008].
Compliant Solution ( ArrayList )
When it is impossible to use the @SuppressWarnings annotation in an appropriate scope,
as in the preceding noncompliant code example, declare a new variable to hold the return
value and adorn it with the @SuppressWarnings annotation.
Click here to view code image
// ...
@SuppressWarnings("unchecked")
T[] result = (T[]) Arrays.copyOf(elements, size, a.getClass());
return result;
// ...
Applicability
Failuretoreducethescopeofthe @SuppressWarnings annotationcanleadtoruntimeex-
ceptions and break type-safety guarantees.
This rule cannot be statically enforced in full generality; however, static analysis can
be used for some special cases.
Bibliography
[API 2013]
Annotation Type SuppressWarnings
[Bloch 2008]
Item 24, “Eliminate Unchecked Warnings”
Search WWH ::




Custom Search