Java Reference
In-Depth Information
Compliant Solution
This compliant solution casts the second operand to type
short
, then explicitly invokes
the
Short.valueOf()
method to create a
Short
instance whose value is
i-1
:
public class ShortSet {
public static void main(String[] args) {
HashSet<Short> s = new HashSet<Short>();
for (short i = 0; i < 100; i++) {
s.add(i);
// Cast of i-1 is safe, because the
// resulting value is always representable
Short workingVal = (short) (i-1);
// ... other code may update workingVal
// Cast of i-1 is safe, because the
// resulting value is always representable
s.remove(((i % 2) == 1) ? Short.valueOf((short) (i-1)) :
workingVal);
}
System.out.println(s.size());
}
}
Asaresultofthecast,thesecondandthirdoperandsoftheconditionalexpressionboth
have type
Short
, and the
remove()
call has the expected result.
Writing the conditional expression as
((i % 2) == 1) ? (short) (i-1)) : work-
ingVal
also complies with this guideline because both the second and third operands in
this form have type
short
. However, this alternative is less efficient because it forces un-
boxing of
workingVal
on each even iteration of the loop and autoboxing of the result of
the conditional expression (from
short
to
Short
) on every iteration of the loop.
Applicability
Whenthesecondandthirdoperandsofaconditionalexpressionhavedifferenttypes,they
can be subject to unexpected type conversions.
Automated detection of condition expressions whose second and third operands are of
different types is straightforward.