基本类型和String比较数据比较实用的是使用工具类比较靠谱:ObjectUtils.equals(Object,Object);
使用apache.common的ObjectUtils是有一个坑
ObejctUtils.equals(参数1,参数2);切记参数1和参数2是同一类型,一个Integer一个Byte就废了。
比较数值过程中:
1、数值类型,值在-128 ~ 127的之间的数值对象,在Integer或者Long....的内部类中IntegerCache中。没有实质性创建对象或者说对象都内部类的cache[]数组中,使用==没有问题返回true,因为是同一对象。
2、数值在-128 ~ 127范围之外的数值类型,都重新创建了对象。再使用“==”,就返回false了。
3、new Integer(0);如果这样写,同样创建了对象,及时值在-128 ~ 127的之间。使用“==”同样返回false;
Integer a = 100;
Integer b = 100;
if (a == b) { // true
System.out.println(true);
} else {
System.out.println(false);
}
a = 100000;
b = 100000;
if (a == b) { // false
System.out.println(true);
} else {
System.out.println(false);
}
//使用equals
if (a.equals(b)) { // true
System.out.println(true);
} else {
System.out.println(false);
}