首页 > 其他 > 详细

判断Integer值相等最好不用==最好使用equals

时间:2017-08-03 14:47:02      阅读:229      评论:0      收藏:0      [点我收藏+]

Integer c = 3;
Integer d = 3;
Integer e = 321;
Integer f = 321;
System.out.println(c == d);
System.out.println(e == f);

输出 true false

 

Integer为对象判断是否相等还是使用equals最靠谱,

int为基本类型,判断是否相等就是可以使用==.

 

原因:

static final Integer cache[] = new Integer[-(-128) + 127 + 1];

static {
      for(int i = 0; i < cache.length; i++) {
             cache[i] = new Integer(i - 128);
      }
}


这是源码,也就是说cache中已有-128到127,不在这范围的会新new ,这时可以理解比较的是内存地址,也就是是不是同个一对象.

所以说当Integer的值不在-128到127的时候使用==方法判断是否相等就会出错,在这个范围之内的就会没有问题!!!

判断Integer值相等最好不用==最好使用equals

原文:http://www.cnblogs.com/songshu120/p/7279327.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!