Effective Java 49 Prefer primitive types to boxed primitives

本文探讨了在Java中使用原始类型相较于装箱类型的优点:更高效、更简洁。文章详细解释了装箱类型可能导致的问题,如NullPointerException,并给出了实际应用场景建议。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

No.

Primitives

Boxed Primitives

1

Have their own values

Have identities distinct from their values

2

Have only fully functional values

Have one nonfunctional value which is null

3

Time and space efficient

Time and space inefficient

   

Note

  • Applying the ==operator to boxed primitives is almost always wrong.

    Comparator<Integer> naturalOrder = new Comparator<Integer>() {

    public int compare(Integer first, Integer second) {

    int f = first; // Auto-unboxing

    int s = second; // Auto-unboxing

    return f < s ? -1 : (f == s ? 0 : 1); // No unboxing

    }

    };

       

  • When you mix primitives and boxed primitives in a single operation, the boxed primitive is auto unboxed.

    public class Unbelievable {

    static Integer i;

    public static void main(String[] args) {

    if (i == 42) // This will invoke an auto-unboxed, since the i is null so there will be a NullPointerException.

    // Fixing the program is as simple as declaring i to be an int instead of an Integer.

    System.out.println("Unbelievable");

    }

    }

       

  • Repeatedly boxed and unboxed will cause the observed performance degradation.

    // This program is much slower than it should be because it accidentally declares a

    // local variable (sum) to be of the boxed primitive type Long instead of the primitive type long.

    public static void main(String[] args) {

    Long sum = 0L;

    for (long i = 0; i < Integer.MAX_VALUE; i++) {

    sum += i;

    }

    System.out.println(sum);

    }

       

    Scenario of using boxed primitives

    • As elements, keys and values in collections since you can't put primitives in collections.
    • As type parameters in parameterized types.(eg.ThreadLocal<Integer>).
    • Making reflective method invocations(Item 53).

       

    Summary

    Use primitives in preference to boxed primitives whenever you have the choice. Primitive types are simpler and faster. Autoboxing reduces the verbosity, but not the danger, of using boxed primitives. When your program compares two boxed primitives with the ==operator, it does an identity comparison, which is almost certainly not what you want. When your program does mixed-type computations involving boxed and unboxed primitives, it does unboxing, and when your program does unboxing, it can throw a NullPointerException. Finally, when your program boxes primitive values, it can result in costly and unnecessary object creations.

转载于:https://www.cnblogs.com/haokaibo/p/prefer-primitive-types-to-boxed-primitives.html

### 解决 `ClassCastException` 异常的方法 当遇到 `java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer` 这样的异常时,表明程序试图将不兼容的数据类型进行强制转换。为了防止此类异常的发生,在处理数据之前应确保其类型匹配。 对于字符串到整数的转换操作,可以采用安全的方式来进行: #### 使用 `Integer.parseInt()` 方法 如果确认源对象确实代表一个有效的整数值,则可以通过将其先转化为字符串形式再利用静态方法 `parseInt(String s)` 来完成转型工作[^3]。 ```java String strNumber = "123"; int number = Integer.parseInt(strNumber); ``` #### 利用 `try-catch` 结构捕获潜在异常 考虑到输入可能不是合法数字的情况,建议加入异常捕捉机制来增强代码健壮性: ```java public static int safeParseInt(Object obj){ try { if(obj instanceof String){ return Integer.parseInt((String)obj); }else{ throw new IllegalArgumentException("Argument is not a string"); } } catch(NumberFormatException e){ System.out.println("Invalid integer format."); return 0; // or any default value you prefer } } ``` 通过上述方式可以在很大程度上减少因不当类型转换而引发的运行期错误。值得注意的是,除了直接使用基本类型的包装类外,还可以考虑应用其他更高级别的抽象如泛型集合框架中的工具函数等,它们往往提供了更为灵活且不易出错的操作接口[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值