Boxing (computer programming): Difference between revisions

Content deleted Content added
Line 29:
</source>
 
Compilers prior to 5.0 would not accept the last line. {{Java|Integer}}s are reference objects, on the surface no different from {{Java|List}}, {{Java|Object}}, and so forth. To convert from an <tt>int</tt> to an Integer, one had to "manually" instantiate the Integer object. As of J2SE 5.0, the compiler will accept the last line, and automatically transform it so that an Integer object is created to store the the value <tt>9</tt><ref>[http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html java.sun.com Java language guide entry on autoboxing]</ref>. This means that, from J2SE 5.0 on, something like <tt>Integer c = a + b;</tt>, where <tt>a</tt> and <tt>b</tt> are Integers themselves, will compile now, because they are unboxed, the integer values summed up, and the result is autoboxed into a new Integer, which is finally stored inside variable <tt>c</tt>. Note that the equality operators cannot be used this way, since the equality operators are already defined for reference types, for equality of the references; to test for equality of the value in a boxed type, one must still manually unbox them and compare the primitives.
 
 
Another example: J2SE 5.0 allows the programmer to treat a collection (such as a {{Java|LinkedList}}) as if it contained <tt>int</tt> values instead of <tt>Integer</tt> objects. This does not contradict what was said above: the collection still only contains references to dynamic objects, and it cannot list primitive types. It can '''not''' be a <tt>List&lt;int></tt>, but it must be a <tt>List&lt;Integer></tt> instead. However, the compiler automatically transforms the code so that the list will "silently" receive objects, while the source code only mentions primitive values. For example, the programmer can now write <tt>list.add(3);</tt> and think as if the int <tt>3</tt> were added to the list; but, the compiler will have actually transformed the line into <tt>list.add(new Integer(3))</tt>.<br/>