Sara :
HashSet charSet = new HashSet();
for (char i = 0; i < 100; i++) {
charSet.add(i);
charSet.remove(i - 1);
}
System.out.println(charSet.size());
HashSet intSet = new HashSet();
for (int i = 0; i < 100; i++) {
intSet.add(i);
intSet.remove(i - 1);
}
System.out.println(intSet.size());
Output is 100 and 1 respectively.
I just realized that short and char do no get auto unboxed in Java. Why didn't the designers think it was important to do that?
Joe C :
This is actually nothing to do with boxing or unboxing.
When you apply an arithmetic operation to a char
, it is converted to an int
, as per JLS §5.6.2:
- Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:
- If either operand is of type
double
, the other is converted todouble
.- Otherwise, if either operand is of type
float
, the other is converted tofloat
.- Otherwise, if either operand is of type
long
, the other is converted tolong
.- Otherwise, both operands are converted to type
int
.
Thus, i - 1
is not a char
, but an int
. And because there are no Integer
s in your charSet
(only Character
s), there is nothing to be removed. If you were to cast i - 1
to a char
, you would get the result you are expecting.