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 ...
随机推荐
- ssl 握手过程【收藏】
收藏几篇关于ssl handshake的好文 http://www.slashroot.in/comment/1242 SSL protocol, does its fantastic job of ...
- jquery判断radioButton是否被选中
so easy HTML: <input type='radio' style='width:20px' id='other' name='projectType' value='其他' /&g ...
- WebGL 3D on iOS8 正式版
今天iOS8终于正式发布了,升级了手头设备后对我来说最重要的就是测试WebGL的3D是否真的能跑苹果的系统了,跑了多个HT for Web的3D例子都非常流畅,比Android刚支持WebGL时好太多 ...
- IOS高级编程之二:IOS的数据存储与IO
一.应用程序沙盒 IOS应用程序职能在系统为该应用所分配的文件区域下读写文件,这个文件区域就是应用程序沙盒.所有的非代码文件如:图片.声音.映象等等都存放在此. 在mac中command+shift+ ...
- mysqlbinlog -v --base64-output 与不加的区别
加-v与加-vv的区别: 加--base64-output=DECODE-ROWS与不加的区别:
- HTTPS 概述
[[ From https与http的区别 ]] 什么是HTTPS HTTPS(Secure Hypertext Transfer Protocol)安全超文本传输协议 它是一个安全通信通道 ...
- 甲骨文白桃花心木P6 EPPM 8.2项目点提供样本
甲骨文白桃花心木样例代码 除非明确确定,这里的示例代码不是认证或Oracle支持;它只是用于教育或测试的目的. 你必须接受 许可协议下载此示例代码. 接受 许可协议 | 下降 许可协议 的名字 ...
- 不可或缺 Windows Native (10) - C 语言: 文件
[源码下载] 不可或缺 Windows Native (10) - C 语言: 文件 作者:webabcd 介绍不可或缺 Windows Native 之 C 语言 文件 示例cFile.h #ifn ...
- 【NOIP训练】【规律+数论】欧拉函数的应用
Problem 1 [题目大意] 给出 多组数据 ,给出 求出 . 题解 证明: 除了 以为均为偶数, 所以互质的个数成对. 由 得 . 所以对于每对的和为 , 共有 对 . 则 Problem ...
- 泛函编程(8)-数据结构-Tree
上节介绍了泛函数据结构List及相关的泛函编程函数设计使用,还附带了少许多态类型(Polymorphic Type)及变形(Type Variance)的介绍.有关Polymorphism的详细介绍会 ...