---
title: "异常的Integer"
author: "剑锋凛冽"
date: "2012-11-19T09:28:49Z"
tags: []
categories: ["编程语言"]
slug: "integer"
draft: false
lastmod: "2012-11-19T09:28:49Z"
id: 1729289
url: "https://swordboy007.iteye.com/blog/1729289"
---

先看下面一段代码

```
public static void main(String[] args) {
		// TODO Auto-generated method stub
		Integer a1=2;
		Integer a2=2;
		System.out.println(a1==a2);
		Integer b1=128;
		Integer b2=128;
		System.out.println(b1==b2);
	}
```

 一般认为Integer是Java提供的int类型包装类，是引用类型，那么a1、a2、b1、b2都是引用类型的对象引用，输出值应该都是false，

但是，实际运行下就会发现确实true、false，也就是说值为2的Integer对象是相同的对象，而128却不是，为什么？

 

实际上，这是因为Integer的在自动拆装箱的实现过程中使用了缓存技术，将-128~127的Integer对象缓存了起来，参见java.lang.Integer的源码

```
private static class IntegerCache {
	private IntegerCache(){}

	static final Integer cache[] = new Integer[-(-128) + 127 + 1];

	static {
	    for(int i = 0; i < cache.length; i++)
		cache[i] = new Integer(i - 128);
	}
    }
```

 这是Integer的一个私有静态内部类，装箱时会自动调用它进行装箱

如上，如果上面的值都是用new Integer生成，就会出现理想中的结果

 

窃以为，这是Java实现的一个败笔，很容易引起误解和错误使用。

参考《Java疯狂讲义》相关章节