Java爬坑--int与Integer的区别,分别什么场合使用

1、Integer是int提供的封装类,而int是Java的基本数据类型

2、Integer默认值是null,而int默认值是0;

3、声明为Integer的变量需要实例化,而声明为int的变量不需要实例化;

4、Integer是对象,用一个引用指向这个对象,而int是基本类型,直接存储数值。

 

int是基本数据类型,Integer是包装类,类似HashMap这样的结构必须使用包装类,

因为包装类继承自Object,都需要实现HashCode,所以可以使用在HashMap这类数据结构中。

 

 1 public static void main(String[] args) {
 2         Integer a = 127;
 3         Integer b = 127;
 4         Integer c = new Integer(127);
 5         Integer d = new Integer(127);
 6         Integer g = Integer.valueOf(127);
 7         Integer h = Integer.valueOf(127);
 8 
 9         Integer e = 256;
10         Integer f = 256;
11 
12         System.out.println(a == b); // true
13         System.out.println(c == d); // false
14         System.out.println(b == c); // false
15 
16         System.out.println(e == f); // false
17         System.out.println(g == h); // true
18         System.out.println(b == g); // true
19 
20     }

要注意的是,new Integer返回的永远是不同的对象,但是当整数范围在-128<i<=127时,Integer.valueOf返回的是同一个对象。

需要理解缓存,即【-128,127】之间的数存在缓存中,可以理解为一个池子,而new出来的对象是在堆内存中,所以Integer a = 1 和 Integer b = new Integer(1)判断“==”永远是false,

不管数字在什么范围;而Integer a = 1 和 Integer b = 1判断==是true,这里的数字就需要在前边所说的范围内

转载于:https://www.cnblogs.com/chuzihang/p/8026427.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值