---
title: "请慎用new Integer()、new Long()……"
author: "xiaoych"
date: "2007-12-10T15:27:20Z"
tags: []
slug: "new-integer-new-long"
draft: false
lastmod: "2007-12-10T15:27:20Z"
id: 147279
url: "https://xiaoych.iteye.com/blog/147279"
---

java 5 引入了自动装箱和自动拆箱的概念。使得开发者不需要注意基本类型如：int long等基本类型和对应的对象类型：Integer Long等之间的转换问题。但是也稍微带来了一点点需要注意的东西。

在java 5 中，要特别注意这些对象之间使用==的问题。


```
  int value = 100;
  Integer a = value;
  Integer b = value;
  System.out.println(a + "==" + b + " ? " + (a == b));
```


输出：**100==100 ? true**


```
  int value = 300;
  Integer a = value;
  Integer b = value;
  System.out.println(a + "==" + b + " ? " + (a == b));
```


输出：**300==300 ? false**

为什么会不一样捏？ 为什么呢？

对比一下反编译的源代码：


```
int value = 100;
Integer a = Integer.valueOf(value);
Integer b = Integer.valueOf(value);
System.out.println((new StringBuilder()).append(a).append("==").append(b).append(" ? ").append(a == b).toString());
int value = 300;
Integer a = Integer.valueOf(value);
Integer b = Integer.valueOf(value);
System.out.println((new StringBuilder()).append(a).append("==").append(b).append(" ? ").append(a == b).toString());
```


看看JDK5的源代码：

```
public static Integer valueOf(int i) {
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache 
    return IntegerCache.cache[i + offset];
}
return new Integer(i);
}
```


原来还有cache的啊…… :shock: 

所以得出两个结果：
**1、慎用 Integer Long Double 等对象请慎用== ，最好转换成基本类型进行对比。
2、尽量少用new Long(x) new Integer(x) 等，尽量使用Integer.valueOf(x) Long.valueOf(x)，这样可以避免过多的new对象，稍微提高一点性能。**