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.

Effective Java 49 Prefer primitive types to boxed primitives的更多相关文章

  1. Effective Java 26 Favor generic types

    Use generic types to replace the object declaration Add one or more type parameters to its declarati ...

  2. Effective Java 35 Prefer annotations to naming patterns

    Disadvantages of naming patterns Typographical errors may result in silent failures. There is no way ...

  3. Effective Java 69 Prefer concurrency utilities to wait and notify

    Principle Use the higher-level concurrency utilities instead of wait and notify for easiness. Use Co ...

  4. Effective Java 18 Prefer interfaces to abstract classes

    Feature Interface Abstract class Defining a type that permits multiple implementations Y Y Permitted ...

  5. Effective Java 25 Prefer lists to arrays

    Difference Arrays Lists 1 Covariant Invariant 2 Reified at runtime Erased at run time 3 Runtime type ...

  6. Effective Java 53 Prefer interfaces to reflection

    Disadvantage of reflection You lose all the benefits of compile-time type checking, including except ...

  7. Effective Java 68 Prefer executors and tasks to threads

    Principle The general mechanism for executing tasks is the executor service. If you think in terms o ...

  8. Effective Java 20 Prefer class hierarchies to tagged classes

    Disadvantage of tagged classes 1. Verbose (each instance has unnecessary irrelevant fields). 2. Erro ...

  9. Effective Java 46 Prefer for-each loops to traditional for loops

    Prior to release 1.5, this was the preferred idiom for iterating over a collection: // No longer the ...

随机推荐

  1. [git]本地查看,重命名,拉取,删除远程分支

    1.git branch -a 查看所有的分支,包含远程仓库.-av:同时显示最近的一个commit信息. 2.git checkout -b newBranch origin/master 拷贝一份 ...

  2. Mysql学习笔记(十一)临时表+视图

    学习内容: 临时表和视图的基本操作... 临时表与视图的使用范围... 1.临时表   临时表:临时表,想必大家都知道这个概念的存在...但是我们什么时候应该使用到临时表呢?当一个数据库存在着大量的数 ...

  3. 一起Polyfill系列:让Date识别ISO 8601日期时间格式

    一.什么是ISO 8601日期时间格式 ISO 8601是国际标准化组织制定的日期时间表示规范,全称是<数据存储和交换形式·信息交换·日期和时间的表示方法>. 示例: 1. 2014-12 ...

  4. 新学C#线程使用总结

    这两天在项目上需要使用多线程技术,研究了半天,碰到了一些问题,现在简要总结下. 线程的使用其实很简单,和JAVA里面差不多,但是还是有很多特别的地方,在C#中的线程,如果要对非线程创建的控件进行操作的 ...

  5. Python入门笔记(26):Python执行环境

    一.python特定的执行环境 在当前脚本继续进行 创建和管理子进程 执行外部命令或程序 执行需要输入的命令 通过网络来调用命令 执行命令来创建需要处理的输出 动态生成Python语句 导入Pytho ...

  6. 重新想象 Windows 8 Store Apps (48) - 多线程之其他辅助类: SpinWait, SpinLock, Volatile, SynchronizationContext, CoreDispatcher, ThreadLocal, ThreadStaticAttribute

    [源码下载] 重新想象 Windows 8 Store Apps (48) - 多线程之其他辅助类: SpinWait, SpinLock, Volatile, SynchronizationCont ...

  7. sql2008 查询字段所属表

    select a.name as 表名, g.*from sysobjects as a left join syscolumns as b on a.id=b.id left JOIN sys.ex ...

  8. 泛函编程(22)-泛函数据类型-Monoid In Action

    在上一节我们讨论了Monoid的结合性和恒等值的作用以及Monoid如何与串类元素折叠算法相匹配.不过我们只示范了一下基础类型(primitive type)Monoid实例的应用,所以上一节的讨论目 ...

  9. Json Utils

    import java.util.List;import java.util.Map; import net.sf.json.JSONArray;import net.sf.json.JSONObje ...

  10. Tomcat/JSP中文编码配置

    来源:http://blog.csdn.net/zhangzikui/article/details/6169978         http://www.iteye.com/topic/300656 ...