Boxing (computer programming): Difference between revisions

Content deleted Content added
Matt Crypto (talk | contribs)
m "by the computer" is not needed
Xaonon (talk | contribs)
slight grammar, style cleanups
Line 4:
 
==Boxing==
 
'''Boxing''' is to place a primitive type within an object so that the primitive can be used as an object, in a language where there is a distinction between a primitive type and an object type. For example, [[list|lists]] may have certain [[methods]] which [[arrays]] might not, but the list might also require that all of its members be objects. In this case, the added functionality of the list might be unavailable to a simple list of numbers.
 
For a more concrete example, in Java, a {{Javadoc:SE|java/util|LinkedList}} can change its size, but an array must have a fixed size. YouOne might desire to have a <code>LinkedList</code> of <code>int</code>s, but the <code>LinkedList</code> class only lists objects &ndash; itobjects—it cannot list primitive types.
 
To get around this, you can box your <code>int</code>s can be boxed into <code>Integer</code>s, which are objects, and then you canadded createto a <code>LinkedList</code> of <code>Integer</code>s. (Using [[generic programming|generic]] parameterized types introduced in [[J2SE]] 5.0, this type is represented as <code>LinkedList<Integer></code>.)
 
===Autoboxing===
 
Autoboxing is the term for treating a primitive type as an object type without any extra code.
 
For example, as of J2SE 5.0, Java will now allow youthe programmer to create a <code>LinkedList</code> of <code>int</code>s. This does not contradict what was said above: Thethe <code>LinkedList</code> still only lists objects, and it cannot list primitive types. But now, when Java expects an object but receives a primitive type, it immediately converts that primitive type to an object.
 
This action is called ''autoboxing'', because it is boxing that is done automatically and implicitly instead of requiring youthe programmer to do itso yourselfmanually.
 
===Unboxing===
 
Unboxing is the term for treating an object type as a primitive type without any extra code.
 
Line 26 ⟶ 29:
Integer k = i + j;
 
The last stepOriginally, inthe particular,compiler doeswould not makeaccept muchthe senselast line. Integers <code>Integer</code>s are objects;, theyon arethe nebuloussurface blocksno ofdifferent from <code>List</code>, somewhere<code>Object</code>, else.and Whatso doesforth; itmathematical meanoperators tosuch addas <code>+</code> were not meaningfully defined for them?. But the following code iswould of course be accepted perfectlywithout okaycomplaint:
 
int i = 9;
Line 32 ⟶ 35:
int k = i + j;
 
As of J2SE 5.0, the first example is now treated just like the second example. The <code>Integer</code> is '''unboxed''' into an <code>int</code>, the two are added, and then the sum is '''autoboxed''' into a new <code>Integer</code>.
 
[[Category:Data types]]