判断Integer值相等最好不用==最好使用equals
2017-08-03 13:52
218 查看
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 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
- [Java]判断Integer值相等最好不用==最好使用equals
- 判断Integer值相等最好不用==最好使用equals(Integer 的值在[-128,127]之间都是可以用==比较的。超过这个区间就得用equals比较)
- 判断Integer值相等最好不用==
- 字符串判断相等最好不用==,用equals通常都对
- 判断Integer值相等最好不用==(未整理)
- 判断Integer值相等最好不用==
- 判断Integer值相等用equals
- jsp中使用equals()判断字符串是否相等时出现的问题(.equals("1")出现的异常)
- Java中判断对象是否相等的equals()方法使用教程
- 不要使用equals方法对AtomicXXX进行是否相等的判断
- 不要使用equals方法对AtomicXXX进行是否相等的判断
- 判断Integer或Long值相等最好不用==
- 什么时候应该使用==?什么时候应该使用Equals?(如何判断值相等还是引用相等。)
- js里没有equals方法,java里string判断相等不能用==
- java中需要用equals来判断两个字符串值是否相等
- WinAPI: EqualRect、EqualSid、EqualPrefixSid - 判断一个矩形(或其他结构)是否相等
- Java判断相等(==和equals方法)
- java基础中Integer值用==和equals判断相等问题解析
- 默认的Equals并非是判断两个对象相等,而是判断是否是同一引用