Home  >  Article  >  Java  >  Item Prefer primitive types over packaged primitive types

Item Prefer primitive types over packaged primitive types

Patricia Arquette
Patricia ArquetteOriginal
2024-10-10 08:09:02495browse

Item  Dê preferência aos tipos primitivos em vez dos tipos primitivos empacotados

Primitive Types vs. Packaged Primitive Types

  • Primitive Types: int, double, boolean, etc.
  • Packed Primitive Types: Integer, Double, Boolean, etc.
  • Java has a dual type system: primitive types and reference types (objects).
  • Each primitive type has a corresponding wrapper class.

Main Differences

  • Identity vs. Value:
    Primitives: They have no identity; two primitives with the same value are always equal.
    Packaged: They are objects and have identity; two objects can have the same value but different identities.

  • Null Values:
    Primitives: Always have a default value (e.g. 0 for int).
    Packaged: May be null, which can lead to NullPointerException exceptions if not handled properly.

  • Performance:
    Primitives: More efficient in terms of time and space.
    Packaged: Introduce overhead due to the creation of additional objects.

Common Problems When Mixing Primitives and Packages

  • 1. Comparison of Identity Instead of Value
  • When comparing objects packaged using ==, you are comparing object references, not the values. This can lead to unexpected results.

Problematic Example:

Comparator<Integer> naturalOrder = (i, j) -> (i < j) ? -1 : (i == j ? 0 : 1);

Problem: The i == j comparison compares references, not values.
Incorrect Behavior: naturalOrder.compare(new Integer(42), new Integer(42)) returns 1 instead of 0.

Solution:
Use the compareTo method or utility methods of the Integer class.

Comparator<Integer> naturalOrder = Integer::compare;

Or, correcting the original comparator:

Comparator<Integer> naturalOrder = (iBoxed, jBoxed) -> {
    int i = iBoxed;
    int j = jBoxed;
    return (i < j) ? -1 : ((i == j) ? 0 : 1);
};

2. Autounboxing and NullPointerException
When using packed types that can be null, autounboxing may throw exceptions if the object is null.

Problematic Example:

Integer i = null;
if (i == 42) {
    System.out.println("Inacreditável");
}

Problem: i is null; when comparing with 42, null autounboxing occurs, resulting in NullPointerException.
Solution: Use primitive types when possible.

int i = 0;
if (i == 42) {
    System.out.println("Inacreditável");
}

3. Degraded Performance due to Autoboxing/Unboxing
Inadvertent use of wrapped types in intensive operations can cause performance degradation due to autoboxing and unnecessary object creation.

Problematic Example:

Long sum = 0L;
for (long i = 0; i <= Integer.MAX_VALUE; i++) {
    sum += i;
}
System.out.println(sum);

Problem: sum is a packed Long; in each iteration, autoboxing/unboxing occurs.

Impact: Much slower code and excessive memory usage.
Solution:
Use primitive types for local variables in intensive operations.

long sum = 0L;
for (long i = 0; i <= Integer.MAX_VALUE; i++) {
    sum += i;
}
System.out.println(sum);

When to Use Packaged Types

  • Collections: You cannot use primitive types in generic collections (e.g. List).
  • Generic Parameters: Generic types do not support primitive types (e.g. ThreadLocal).
  • APIs that Require Objects: Certain APIs require objects instead of primitive types.

Good Practices

  • Prefer Primitive Types: Whenever possible, use primitive types for simplicity and efficiency.
  • Be careful with Autoboxing/Unboxing: Autoboxing reduces verbosity but can introduce subtle errors.
  • Avoid Comparisons with == in Wrapped: Use methods like equals() or compare the unwrapped values.
  • Check for Nulls: When working with packaged types, be aware that they can be null and cause NullPointerException.

Summary
Primitive Types:
Simpler and faster.
They cannot be null.
They have no identity (only value).

Packaged Types:
Required for use in collections and generic APIs.
They can be null.
They have object identity.

The above is the detailed content of Item Prefer primitive types over packaged primitive types. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn