int和Integer有什么区别
区别
int
是基本数据类型,Integer
是引用数据类型。int
默认值是0,Integer
默认值是null。int
类型直接存储数据,Integer
需要实例化对象,指向对象的地址。
自动拆箱和自动装箱
- 自动装箱:将基本数据类型转换为引用数据类型(对象)。
- 自动拆箱:将引用数据类型转换为基本数据类型
- 代码示例:
public class Dome {
public static void main(String[] args) {
Integer a = new Integer(1);
//自动装箱 《==》Integer a = new Integer(1);
Integer b = 1;
//自动拆箱 对象不能直接进行计算,将对象a转换成基本数据类型
int c = a - 2;
System.out.println("a:"+a+" b:" +b+" c"+c);
}
}
注意
- 查看Integer类部分源代码方法:
hashCode
@Override
public int hashCode() {
//hashCode 为integer的值
return Integer.hashCode(value);
}
equals
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();//手动拆箱 ==》比较两个Integer的值
}
return false;
}
valueOf
public static Integer valueOf(int i) {
//-128~127会被加载到内存,其他会new一个对象
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
- 比较两个Integer对象:
(a)情况一:
public class Dome {
public static void main(String[] args) {
Integer a = new Integer(1);
Integer b = new Integer(1);
System.out.println("a:"+a.hashCode()+" b:"+b.hashCode());
System.out.println(a.equals(b));
System.out.println(a==b);
}
}
结果:通过上面的源码不难理解hashCode和equals的值,两个对象都是new出来的,地址肯定不同。
a:1 b:1
true
false
(b)情况二:
public class Dome {
public static void main(String[] args) {
Integer a = 1;
Integer b = 1;
System.out.println("a:"+a.hashCode()+" b:"+b.hashCode());
System.out.println(a.equals(b));
System.out.println(a==b);
}
}
结果:我们可以看到 a和b是同一个对象,这是因为JVM中一个字节一下的整型数据(即[-128,127])会在JVM启动时加载进内存,所以除非用new Integer()显示的创建对象,否则都是同一对象。
a:1 b:1
true
true
(c)情况3
public class Dome {
public static void main(String[] args) {
Integer a = 130;
Integer b = 130;
System.out.println("a:"+a.hashCode()+" b:"+b.hashCode());
System.out.println(a.equals(b));
System.out.println(a==b);
}
}
结果:这就和情况二的原因是相同,当数值大于127或者小于-128时会重新new一个,在这之间的数会加载进入内存,Integer a = 130;
会被编译成Integer a = Integer.valueOf(130);
,我们查看源代码,130>127会new一个对象,a和b都是new出来的对象,地址一定不相等。
a:130 b:130
true
false
(d)情况四
public class Dome {
public static void main(String[] args) {
int a = 1;
Integer b = new Integer(1);
System.out.println(a==b);
}
}
结果:封装类和基本数据类型比较的时候,会自动拆箱,比较数值是否相等。
true