==和equals方法的区别以及Integer和String的应用

==和equals方法的区别以及Integer和String的应用

== 比较的是两个对象的地址内存地址,而equals比较的是两个对象的值。
例如String的equals比较方法,先调用==判断是否相同,然后再判断对象value的char数组是否相同。
建议:比较两个对象是否相同,统一使用Objects.equals方法,阿里规约有推荐

Integer和int的==操作

Integer和int的==判断主要是地址的判断。示例如下

int i = 100;
Integer i1 = 100; 
System.out.println(i==i1);//true
Integer i2 = 100;
System.out.println(i1==i2);//true
Integer i3 = new Integer(100);
System.out.println(i==i3);//true
System.out.println(i1==i3);//false		
Integer i4 = 300;
Integer i5 = 300;
System.out.println(i4==i5);//false
Integer i6 = new Integer(300);
System.out.println(i4==i6);//false
int i6=300;
System.out.println(i5==i6);///true

原因说明:1 自动装箱和Integer对象缓存数组 :int i = 100,涉及到自动装箱,即Integer i = Integer.valueOf(100);,另外Integer有缓存数组,即-128<=value<=127,都从缓存数组中获取Integer对象。因此ii1,i1i2是true,但是如果通过new Integer方法生成的对象,是false,因为new的本意就是创见一个新对象,因此i3i1为false,而ii3的原因是,int与Integer比较时,Integer会进行拆箱,比较value的大小,因此相同。
2 i4
i6 因为都是Integer对象,并且value超出缓存的最大值,因此都是new的对象,因此Integer对象比较时为false
3 i5==i6 因为i5是int,i6就会拆箱,这样就不是比较内存地址,而是比较数值。
4 因此如果要是判断两个Integer对象的大小是否相同,要使用Integer.intValue()进行判断,如果一个Integer和int进行大小判断,就不需要采用Integer.intValue(),因为Integer与int比较是会自动拆箱,或者直接使用Integer的equals方法

String的==和equals

String str = "abc";
String str1 = "abc";
System.out.println(str==str1);//true
String str2 = new String("abc");
System.out.println(str==str2);//false
String str3 = new String("abc");
System.out.println(str2==str3);//false

因为String同样有字符串常量池,因此当通过str==str1,两者都是直接从常量池中获取对象。但是通过new的方式,无论字符串常量池中是否有该值,都会新建对象并存储该值。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值