Java Reference
In-Depth Information
Noncompliant Code Example (Object)
Thisnoncompliantcodeexamplesumsasetofnumbersusingavariablearitymethodthat
uses
Object
asthevariablearitytype.Consequently,thismethodacceptsanarbitrarymix
ofparametersofanyobjecttype.Legitimateusesofsuchdeclarationsarerare(butseethe
“Applicability” section of this guideline).
double sum(Object... args) {
double result = 0.0;
for (Object arg : args) {
if (arg instanceof Byte) {
result += ((Byte) arg).byteValue();
} else if (arg instanceof Short) {
result += ((Short) arg).shortValue();
} else if (arg instanceof Integer) {
result += ((Integer) arg).intValue();
} else if (arg instanceof Long) {
result += ((Long) arg).longValue();
} else if (arg instanceof Float) {
result += ((Float) arg).floatValue();
} else if (arg instanceof Double) {
result += ((Double) arg).doubleValue();
} else {
throw new ClassCastException();
}
}
return result;
}
Compliant Solution (Number)
This compliant solution defines the same method, but uses the
Number
type. This abstract
class is general enough to encompass all numeric types, yet specific enough to exclude
nonnumeric types.
double sum(Number... args) {
// ...
}