Question

My question is what are the advantages and disadvantages between using boxed primitives in an Java application over using primitives?

Here are some advantages and disadvantages that may or may not be correct:

One advantage is that null is allowed so the type aligns closer with database types which likely allow nulls.

Another advantage of boxed primitives is that creating defensive copies does not require you to initialize another primitive type, only the pointer to one, which may save time.

One disadvantage of boxed primitives is they are more expensive in terms of performance than primitives, but the popular opinion seems to be the expense is worth worrying about later on in development when and if performance becomes an issue.

Another disadvantage is it seems that comparing boxed primitives with '==' will cause the pointers to be compared instead of the underlying types.

Do you have feedback on these advantages or disadvantages and do you know of any others?

Thanks in advance.

Était-ce utile?

La solution

The biggest advantage of boxed primitives over the regular ones is the ability to use them in the standard Java collections. It is possible to make, say, an ArrayList<Integer>, but not ArrayList<int>.

Their biggest disadvantage is the costs, both in terms of memory and in terms of performance: depending on the architecture and the underlying type, the cost in terms of memory may go as much as nine times (consider boxing a byte on a 64-bit platform). The cost in performance is twofold: you need extra cycles for unboxing every time you need the value, but more importantly, the memory footprint influence the order in which the actual memory is accessed, which may reduce the efficiency of the CPU data caching.

The other advantages/disadvantages that you have listed apply as well:

  • Boxed primitives are nullable,
  • You do not need to copy a value, only a reference (this saves you time and space only when the size of a reference is smaller than the size of the data, e.g. when you have a Long on a 32-bit platform).
  • Boxed primitives are harder to compare for equality/inequality.

The "defensive copying" point does not apply, because all boxed primitives in Java are immutable.

Autres conseils

Collections frameworks and Generics exclusively use objects. So boxing becomes essential. In Generics Java does something called a Type Erasure.

When the compiler finds the definition of a generic type or method, it removes all >occurrences of the type parameters and replaces them by their leftmost bound, or type >Object if no bound had been specified.

This means you can never have a primitive type in Generics.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top