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 ...
随机推荐
- python——第一天
两种循环: for x in …… while range(n) 生成整数序列,并且是从0开始一直到n-1的整数 raw_input() 读取的内容永远以字符串的形式,必须先用 int() 把字符串转 ...
- SQL Server里因丢失索引造成的死锁
在今天的文章里我想演示下SQL Server里在表上丢失索引如何引起死锁(deadlock)的.为了准备测试场景,下列代码会创建2个表,然后2个表都插入4条记录. -- Create a table ...
- js-初步了解
一.javascript的由来 Javascript是一种web技术,最初起名叫LiveScript,它是Netscape开发出来一种脚本语言,其目的是为了扩展基本的Html的功能,用来替代复杂的CG ...
- Java中接口式的匿名内部类的构造方法
在使用多线程的时候,时常会使用两种方式实现,一种是直接继承Thread类来实现多线程,另外一种就是实现Runnable接口. 我们都知道,接口是没有构造方法的,同时匿名内部类也是没有构造方法的.原因有 ...
- tomcat端口被占用
这里就以win7为例进行讲解. 首先打开cmd,打开的方法很简单,在开始菜单中直接输入即可.同样也可以按下win+R打开运行,然后输入cmd即可. 在dos命令中输入以下命令查询正在被使用的端口号以及 ...
- List<?>和List<T>的区别?
出自:https://www.zhihu.com/question/31429113
- Node.js下基于Express + Socket.io 搭建一个基本的在线聊天室
一.聊天室简单介绍 采用nodeJS设计,基于express框架,使用WebSocket编程之 socket.io机制.聊天室增加了 注册登录模块 ,并将用户个人信息和聊天记录存入数据库. 数据库采用 ...
- 【jQuery基础学习】06 jQuery表单验证插件-Validation
jQuery的基础部分前面都讲完了,那么就看插件了. 关于jQuery表单验证插件-Validation validation特点: 内置验证规则:拥有必填.数字.E-Mail.URL和信用卡号码等1 ...
- csharp: MVC Controls
http://mvccontrolstoolkit.codeplex.com/ MVC Controls Toolkit http://mvcjquerycontrols.codeplex.com/ ...
- question about import google file
1. question descibe; once, one css file(app.css) of my web project has sentence like this: @import u ...