Item 49: Prefer primitive types to boxed primitives

1.  There are three major differences between primitives and boxed primitives. First, primitives have only their values, whereas boxed primitives have identities distinct from their values. Second, primitive types have only fully functional values, whereas each boxed primitive type has one nonfunctional value, which is null, in addition to all of the functional values of its corresponding primitive type. Last, primitives are generally more time- and space-efficient than boxed primitives.

 

2.  Applying the == operator to boxed primitives is almost always wrong.

 

3.  When your program does mixed-type computations involving boxed and unboxed primitives, the boxed primitive is auto-unboxed. If a null object reference is auto-unboxed, you get a NullPointerException.

 

4.  Boxed primitives have several legitimate uses. The first is as elements, keys, and values in collections. You can’t put primitives in collections, so you’re forced to use boxed primitives. This is a special case of a more general one. You must use boxed primitives as type parameters in parameterized types, because the language does not permit you to use primitives. Finally, you must use boxed primitives when making reflective method invocations.

 

5.  Use primitives in preference to boxed primitives whenever you have the choice. Primitive types are simpler and faster.

 

你可能感兴趣的:(unboxing,Primitive,boxed primitive,boxing)