Sunday, 11 October 2009

Item 49: Prefer primitive types to boxed primitives

This is the first item, certainly that I have reviewed, where I feel Bloch has it spot on. There's no arguing with this one!

Bloch points out that Java has a number of primitive types such as int, double and boolean and each of these types has a corresponding reference type: Integer, Double and Boolean. These are the boxed primitives. Auto-boxing and auto-unboxing was introduced into the language in 1.5, so the Java programmer must now be more mindful of their use.

There are three main differences between primitive types and boxed primitives:

  • Primitives have only their values, whereas boxed primitives have identities distinct form their values

  • Primitive types cannot be null, but boxed primitives can

  • Primitive types are more space and time efficient than boxed-primitives

Care must be taken with using the == operator with boxed primitives as, with any other reference type, it compares identity and you almost certainly want to be comparing value. If a boxed primitive is compared to a primitive with the == operator, the primitive type is boxed and the identities compared, so care must also be taken here.

The process of boxing and unboxing, especially in a loop can serious impede performance.

Basically, boxes primitives should be avoided unless primitive types cannot be used, such as in collections or as parameterised types.

No comments:

Post a Comment