前言
Java中有两种数据类型

- 基本数据类型
基本数据类类型存的是数值本
- 引用数据类型
引用类型变量在内存放的是数据的引用
正文
/**
* @author Lee Boynton
* @author Arthur van Hoff
* @author Josh Bloch
* @author Joseph D. Darcy
* @since JDK1.0
*/
public final class Integer extends Number implements Comparable<Integer> {
//省略...
}
Integer是一个class类。
区别:
- Integer是引用数据类型,int是基本数据类型。
- Integer 是类,默认值为null,int是基本数据类型,默认值为0。
- Integer 表示的是对象,用一个引用指向这个对象,而int是基本数据类型,直接存储数值。
延伸:
先看下面的代码片段
public static void main(String[] args) {
Integer a = 27;
Integer b = 27;
System.out.println(a == b);
Integer c = 200;
Integer d = 200;
System.out.println(c == d);
int aa = 27;
System.out.println(aa == a);
Integer e = new Integer(27);
Integer f = new Integer(27);
System.out.println(e == f);
}
打印的结果是:
true
false
true
false
结果为什么是这样,继续往下看:
Integer 的自动拆箱和装箱
自动装箱
Integer it = 27;
反编译之后查看代码变成了:
Integer it = Integer.valueOf(27);
这就是基本数据类型的自动装箱,27是基本数据类型,然后被解析成Integer类。
自动拆箱
Integer it = new Integer(27);
int a = it;
反编译之后查看代码变成了:
Integer it = new Integer(27);
int a = it.intValue();
简单来说:装箱就是把基础类型封装成一个类。比如把int封装成Integer,这时你就不能把他当成一个数了,而是一个类了,对他的操作就需要用它的方法了。拆箱就是把类转换成基础类型。
回到上面的问题,如果经过自动装箱和拆箱后我们在看代码片段,就变成了:
public static void main(String[] args) {
Integer a = Integer.valueOf(27);
Integer b = Integer.valueOf(27);
System.out.println(a == b);
Integer c = Integer.valueOf(200);
Integer d = Integer.valueOf(200);
System.out.println(c == d);
int aa = 27;
System.out.println(aa == a.intValue());
Integer e = new Integer(27);
Integer f = new Integer(27);
System.out.println(e == f);
}
打印的结果是:
true
false
true
false
我们先来分析一下源码:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
int h = 127;
//省略...
high = h;
}
//省略...
}
结论:java为了提高效率,IntegerCache类中有一个数组缓存了值从-128到127的Integer对象。当我们调用Integer.valueOf(int i)的时候,如果i的值是>=-128且<=127时,会直接从这个缓存中返回一个对象,否则就new一个Integer对象。
所以:
- a 和 b 在缓存表示范围内, 并且是同一个对象,所以为 true。
- 200是不在-128到127之间的,第一次创建对象的时候没有缓存,第二次创建了一个新的Integer对象。故打印结果为false。
- Integer 的自动拆箱功能,也就是比较两个基本数据类型,所以为true。
- 因为这个虽然值为27,但是都是通过 new 关键字来创建的两个对象,是不存在缓存的概念的。结果当然为 false。
网友评论