【JAVA】Java中equals与“==”的区别详解;获取内存地址

该文章详细解释了在Java中,对象的equals方法与==运算符的区别,特别是在处理Integer对象时。通过示例代码展示了当Integer值在缓存范围内(-128到127)时,==比较的是引用是否相同,而equals则检查数值是否相等。此外,还使用VM.current().addressOf()函数展示了不同对象在内存中的不同地址。
摘要由CSDN通过智能技术生成

推荐好文:Java中equals与“==”的区别详解

查看内存地址函数

import org.openjdk.jol.vm.VM;

VM.current().addressOf()

实例:

import org.openjdk.jol.vm.VM;

public class passbyValue_Reference {
    public static void main(String[] args) {
        Integer a = 100;
        Integer b = 100;

        Integer c = 128;
        Integer d = 128;

        Integer x = 127;
        Integer y = 127;

        System.out.println("a = 100 address: " + VM.current().addressOf(a));
        System.out.println("b = 100 address: " + VM.current().addressOf(b));

        System.out.println("c = 128 address: " + VM.current().addressOf(c));
        System.out.println("d = 128 address: " + VM.current().addressOf(d));

        System.out.println(a == c); // false
        System.out.println(b == d); // false

        System.out.println(a == b); // true
        System.out.println(a.equals(b)); // true

        System.out.println(c == d); // false
        System.out.println(c.equals(d)); // true

        System.out.println(x == y); // true
        System.out.println(x.equals(y)); // true

        /*
        // 定义一个Integer变量时,会默认进行Integer.valueOf(a)操作
        public static Integer valueOf(int i) {
            assert IntegerCache.high >= 127;
            if (i >= IntegerCache.low && i <= IntegerCache.high)
                return IntegerCache.cache[i + (-IntegerCache.low)];
            return new Integer(i);
        }
        */
    }
}

输出

a = 100 address: 31911821712
b = 100 address: 31911821712
c = 128 address: 31913988872
d = 128 address: 31913988888
false
false
true
true
false
true
true
true
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值