int p1 = 1; int p2 = 1; Integer i = 1000; Integer j = 1000; Integer a = 1; Integer b = 1; Integer k = new Integer(1); Integer h = new Integer(1); System.out.println("==:"+(p1==p2)); System.out.println("==:"+(i==j)+" equals:"+i.equals(j)); System.out.println("==:"+(a==b)+" equals:"+a.equals(b)); System.out.println("==:"+(h==k)+" equals:"+h.equals(k));
不足支持请多多指教,谢谢==:true //p1进栈后去常量池找值,没找到就创建,当p2进栈后常量池有一个1,
所以直接指向这个内存地址 ==:false equals:true //Integer自动装箱有一个范围[-128,127],所以这里比较的是堆内存地址
所以是"==:"false,"equals:"true是因为Integer重写了equals()方法;
==:true equals:true
==:false equals:true //"=="比较的是堆内存地址,显然是false,"equals:"true 同上
总结一下:
对象==对象 比的是对象的内存地址 对象==它对应的基本类型变量 比的是对象里边的value跟
基本类型变量的内存地址
Double 底层:
public static Double valueOf(String s) throws NumberFormatException { return new Double(parseDouble(s)); }返回的是new对象,所以"==:"false,"equals:"trueFloat 底层:public static Float valueOf(String s) throws NumberFormatException { return new Float(FloatingDecimal.getThreadLocalInstance().readJavaFormatString(s).floatValue()); }返回的是new对象,所以"==:"false,"equals:"trueInteger 底层:Character 底层:public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }在[-128,127],"==:"true,"equals:"true;反之"==:"false,"equals:"truepublic static Character valueOf(char c) { if (c <= 127) { // must cache return CharacterCache.cache[(int)c]; } return new Character(c); }在<=127,"==:"true,"equals:"true;反之"==:"false,"equals:"trueString 底层:public static String valueOf(Object obj) { return (obj == null) ? "null" : obj.toString(); }Long 底层:"==:"true,"equals:"true;public static Long valueOf(long l) { final int offset = 128; if (l >= -128 && l <= 127) { // will cache return LongCache.cache[(int)l + offset]; } return new Long(l); }在[-128,127],"==:"true,"equals:"true;反之"==:"false,"equals:"true