I have some difficulty understanding the following part from Programming Language Pragmatics, by Scott
C# and more recent versions of Java perform automatic boxing and unboxing operations that avoid the wrapper syntax in many cases:
ht.put(13, 31); int m = (Integer) ht.get(13);
Here the Java compiler creates hidden Integer objects to hold the values 13 and 31, so they may be passed to put as references. The Integer cast on the return value is still needed, to make sure that the hash table entry for 13 is really an integer and not, say, a floating-point number or string. Generics, which we will consider in Section 7.3.1, allow the programmer to declare a table containing only integers. In Java, this would eliminate the need to cast the return value. In C#, it would eliminate the need for boxing.
I was wondering what it means by "The Integer cast on the return value is still needed, to make sure that the hash table entry for 13 is really an integer and not, say, a floating-point number or string"? Note that this is in Java.
In
int m = (Integer) ht.get(13);
, does it use boxing (by(Integer)
) during unboxing (assignment toint
)?Specifically, does
(integer)
convert its operand to an object of theInteger
class? But its operandht.get(13)
is already anInteger
object, and now the assignment expects a value of builtin typeint
. So don't we need a conversion fromInteger
toint
here?How does generics "eliminate the need to cast the return value" in Java ?
In C#, how would it "eliminate the need for boxing"?
Thanks.