In Java 5, I can implicitly convert a short to an Integer in two steps like this:
List<Integer> list = new ArrayList<Integer>();
short s = 5;
// Lines below do compile.
int shortFromInt = s;
list.add(shortFromInt);
However, I can't combine those two steps into one step like this:
// Line below doesn't compile.
list.add(s);
It seems like type conversion should be transitive. So, what is the philosophical reasoning for not allowing the second example, while allowing the first?
> It seems like type conversion should be transitive. So, > what is the philosophical reasoning for not allowing the > second example, while allowing the first?
I don't think there is a philisophical reason, rather, there is a technical reason.
list.add(s);
The above is equivalent to this:
list.add(Short.valueOf(s))
which returns a Short. There is no conversion from Short to Integer.
There is no type convesion between primitive types and objects in Java language. Your code shows the new autoboxing feature in Java 5.
List<Integer> list = new ArrayList<Integer>();
short s = 5;
int shortFromInt = s; // short type is converted to int type implicitly
list.add(shortFromInt); // int type is autoboxed to Integer type.
list.add(s); // short type is autoboxed to Short type, but "list" can only contain Integer type elements.