Java Reference
In-Depth Information
Set s = new HashSet();
public final void doLogic(int a, char c) {
s.add(a);
s.add(c); // Type-unsafe operation, ignored
}
}
This code is dangerous because all unchecked warnings within the class are sup-
pressed. Oversights of this nature can result in a ClassCastException at runtime.
Compliant Solution
Limit the scope of the @SuppressWarnings annotation to the nearest code that generates
a warning. In this case, it may be used in the declaration for the Set :
Click here to view code image
class Legacy {
@SuppressWarnings("unchecked")
Set s = new HashSet();
public final void doLogic(int a, char c) {
s.add(a); // Produces unchecked warning
s.add(c); // Produces unchecked warning
}
}
Noncompliant Code Example ( ArrayList )
This noncompliant code example is from an old implementation of java.util .Ar-
rayList :
Click here to view code image
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
if (a.length < size) {
// Produces unchecked warning
return (T[]) Arrays.copyOf(elements, size, a.getClass());
}
// ...
}
Search WWH ::




Custom Search