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

推荐好文: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

猜你喜欢

转载自blog.csdn.net/xiaoyue_/article/details/129850653