先说一个问题:为什么在JavaBean里定义整型时使用Integer而不是int
A:这与数据库查询有关,当某个字段没有值的时候Integer会为null,而int会默认返回0.
我从几个点来认识:
1.int和Integer的区别
2.int和Integer的转换(装箱与拆箱)
3.例子展示
1.区别与联系
- int是基本数据类型,Integer是一个类。That means: int可直接定义使用,Integer需要初始化
- 基本数据类型一般用于数据运算,而Integer可以调用方法进行其它操作
2.拆箱和装箱
装箱:将基本数据类型封装成类
——其实就是构造一个Integer对象,初始化Integer对象时使用基本数据类型的值赋值给value属性
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i); //[-128, 127]之外的值就会重新new
}
// 赋值给value属性
public Integer(int value) {
this.value = value;
}
拆箱:从包装类中得到基本数据类型
——其实就是获取value的属性值
// 其实就是获取了value属性
public int intValue() {
return value;
}
什么时候装箱? 当基本数据类型赋值给包装类时
什么时候拆箱? 当基本数据类型与包装类做运算时
3.例子展示
我从其它博客copy的示例
Integer a = 99; //自动装箱 相当于调用了Integer的valueOf()函数
int b = a;//自动拆箱 调用了intValue()函数
Integer a1=10;
int a2=10;
System.out.println(a2==a1) //true
Integer a1 = 200;
Integer a2 = 200;
System.out.println(a1==a2);// false
第二个为什么会false?
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
可以知道,在cache数值范围之外Integer对象是通过new得到的
上面代码涉及到一个缓存数组cache,它是Integer类型,里面的静态块初始化了Cache数组。
默认状态下,Cache数组的值在[-128, 127]之间。
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
}
high = h;
cache = new Integer[(high - low) + 1]; //256
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}
private IntegerCache() {}
}