Home >Java >javaTutorial >Item Prefer primitive types over packaged primitive types
Primitive Types vs. Packaged Primitive Types
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
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
Good Practices
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!