"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Item Prefer primitive types over packaged primitive types

Item Prefer primitive types over packaged primitive types

Published on 2024-11-11
Browse:846

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

Primitive Types vs. Packed Primitive Types

  • Primitive Types: int, double, boolean, etc.
  • Packed Primitive Types: Integer, Double, Boolean, etc.
  • Java has a double 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 an identity; two objects can have the same value but different identities.

  • Null Values:
    Primitives: Always have a default value (e.g. 0 for int).
    Packed: 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. Identity Instead of Value Comparison
  • When comparing objects packaged using ==, you are comparing object references, not the values. This can lead to unexpected results.

Problematic Example:

Comparator naturalOrder = (i, j) -> (i 



Problem: Comparison i == j 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 naturalOrder = Integer::compare;

Or, correcting the original comparator:

Comparator naturalOrder = (iBoxed, jBoxed) -> {
    int i = iBoxed;
    int j = jBoxed;
    return (i 



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 



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 



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.
  • Beware of 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).

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

Release Statement This article is reproduced at: https://dev.to/giselecoder/item-61-de-preferencia-aos-tipos-primitivos-em-vez-dostipos-primitivos-empacotados-34fk?1 If there is any infringement, please contact study_golang@163 .comdelete
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3