自动装箱

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:"true
Float 底层:
public static Float valueOf(String s) throws NumberFormatException {
    return new Float(FloatingDecimal.getThreadLocalInstance().readJavaFormatString(s).floatValue());
}
返回的是new对象,所以"==:"false,"equals:"true
Integer 底层:
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:"true
Character 底层:
public 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:"true
String 底层:
public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}
"==:"true,"equals:"true;

Long 底层:
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




不足支持请多多指教,谢谢
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值