1.==与equals
A:Integer
话不多说,Integer这种封装类为什么建议使用equals?是不是必须用equals?对于第二个问题,答案是否定的,其实原因都在源码里:
public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }在区间[IntegerCache.low,IntegerCache.high]之间,Integer是不会new新的对象,此时只用==也是可以可行的,当超出这个范围后就必须使用equals了,IntegerCache的具体范围如下:
private static class IntegerCache { static final int low = -128; static final int high; static final Integer cache[]; static { // high value may be configured by property int h = 127; String integerCacheHighPropValue = sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high"); if (integerCacheHighPropValue != null) { try { int i = parseInt(integerCacheHighPropValue); i = Math.max(i, 127); // Maximum array size is Integer.MAX_VALUE h = Math.min(i, Integer.MAX_VALUE - (-low) -1); } catch( NumberFormatException nfe) { // If the property cannot be parsed into an int, ignore it. } } high = h; cache = new Integer[(high - low) + 1]; int j = low; for(int k = 0; k < cache.length; k++) cache[k] = new Integer(j++); // range [-128, 127] must be interned (JLS7 5.1.7) assert IntegerCache.high >= 127; } private IntegerCache() {} }B:浮点数
此处考虑的浮点数的相等不会去计较值类型与封装类型的相等,而是原始类型的大小是否相等,通过以下例子
public class Test{ public static void main(String[] args){ isEqualOfFloat(10.222222225f, 10.222222229f); } public static void isEqualOfFloat(float a, float b){ System.out.println("a:" + a+" b:" + b); System.out.println("-------使用“==”符号比较是否相等:" + (a==b)); System.out.println("-------使用“Math.abs()”方法比较是否相等:" + (Math.abs(a-b)>0) ); System.out.println("-------使用“Math.abs()”方法比较是否相等(比较宽容的限制):" + (Math.abs(a-b)<0.00000001) ); System.out.println("-------比较大小“<”:" + (a<b)); System.out.println("-------比较大小“>”:" + (a>b)); } }执行结果 a:10.222222 b10.222222 a.toString():10.222222 b.toString():10.222222 -------使用“==”符号比较是否相等:true -------使用“Math.abs()”方法比较是否相等:false -------使用“Math.abs()”方法比较是否相等(比较宽容的限制):true -------比较大小“<”:false -------比较大小“>”:falsefloat a、b都失去了自己的精度,变得相等,写了很多有效位数,其实并没有效果,结论就是用浮点数比较的两个数字只是大体相等,并不一定完全相等,使用Math.abs(a-b) == 0,判断最为合适,比较精确的数字比较还是建议使用BigDecimal这个数字类
C:String相等
原理懒得讲,请无脑使用StringUtils.equals(str1,str2),方法比较相等
2.对象相等
hashcode与equals
3.时间相等
时间戳比较
4.class相等
名字与classloader
5.文件相等
MD5
6.json相等
7.接口相等(幂等)
8.应用部署的无状态
