Effective Java 49 Prefer primitive types to boxed primitives
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的更多相关文章
- Effective Java 26 Favor generic types
Use generic types to replace the object declaration Add one or more type parameters to its declarati ...
- Effective Java 35 Prefer annotations to naming patterns
Disadvantages of naming patterns Typographical errors may result in silent failures. There is no way ...
- 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 ...
- Effective Java 18 Prefer interfaces to abstract classes
Feature Interface Abstract class Defining a type that permits multiple implementations Y Y Permitted ...
- Effective Java 25 Prefer lists to arrays
Difference Arrays Lists 1 Covariant Invariant 2 Reified at runtime Erased at run time 3 Runtime type ...
- Effective Java 53 Prefer interfaces to reflection
Disadvantage of reflection You lose all the benefits of compile-time type checking, including except ...
- 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 ...
- Effective Java 20 Prefer class hierarchies to tagged classes
Disadvantage of tagged classes 1. Verbose (each instance has unnecessary irrelevant fields). 2. Erro ...
- 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 ...
随机推荐
- web前端学习路线与书籍推荐
什么是web前端? 在以前,通俗的讲是网页制作,在现在,哼哼,可以参考这篇文章 http://tieba.baidu.com/p/4817153404 那么如果高效优雅的学习web呢? 注:以下纯属个 ...
- intellij 调试方法
intellij 调试方法 转自 http://www.th7.cn/Program/net/201410/296492.shtml
- CentOS6.5菜鸟之旅:安装Realtek无线网卡驱动
一.前言 CentOS6.5不像CentOS7和Unbuntu那样自动安装好了无线网卡驱动,因此需要我们折腾一下. 二.安装前的准备工作 [a] 检查无线网卡驱动的安装情况(通过查看网络接口的安装 ...
- 【循序渐进学Python】5.Python常用流程控制及其他语句
1. 赋值语句常用技巧 通过序列解包(sequence unpacking)可以将多个值的序列解开,让后一一放置到变量的序列中.解包的序列中的元素必须和等号左边变量数量一致.如下: values = ...
- 简单介绍.Net3.0 中跨线程访问控件
这两天用WPF做一个项目的UI部分时,发现跨线程地访问了UI控件,自然地报异常了.当时找了半天也没在控件中找到InvokeRequired属性和Invoke方法,郁闷之极.....最后发现在.net3 ...
- android dp
http://www.see-say.com/viewnews-47657.html http://cn.club.vmall.com/thread-970026-1-1.html http://ww ...
- Webhooks PHP
Webhooks/Parse When webhooks are triggered in the gateway, a notification is sent as a POST request ...
- flask-uploads扩展的使用笔记
涉及的flask扩展 flask-uploads flask的一个文件上传扩展, 提供了UploadSet这个概念 flask-wtf(中文) 很强大的表单的扩展 flask-bootstrap bo ...
- 一、PBNI环境搭建及初步使用
PowerBuilder Native Interface(PowerBuilder本机接口PBNI)允许将第3方程序转换为PowerBuilder对象,供PowerBuilder直接使用,也允许将P ...
- ElasticSearch文档-简单介绍
ElasticSearch是一个基于Lucene构建的开源,分布式,RESTful搜索引擎.设计用于云计算中,能够达到实时搜索,稳定,可靠,快速,安装使用方便.支持通过HTTP使用JSON进行数据索引 ...