直接上验证结果:

1 .直接声明的 不管是Long 还是long  -128 -127 之间使用 ==  和 equlas 都是true 因为 Long包对 常用的做了缓存。如果在这个区间直接从cache 中取。所以 == 地址值也是一样的 为true

 2 new 出来的 必须使用equals .虽然做了-128 -127 做了缓存,但是new出来的是新分配的内存,地址值不一样 使用==  数值即使一样也为false.

3 使用 == 不管是直接声明的,还是new出来的 ,只要一边有基本数据类型 都可以正常对比。会自动拆箱。例如:

因为下面 int和long 属于基本类型。所以 == 会将Long 拆箱成long  直接比较数值  

Long e = 300L; int f = 300;
Long g = 300L; long h = 300L;
System.out.println("Long与int 300 equals 结果" + (e == f));//true
System.out.println("Long与long 300L equals 结果" + (g == h));//true
 public static void main(String[] args) {


        // 首先知道Long 是引用类型 == 对比的是地址值, long 是基本类型 == 比较的是值
        /*    Long 类对部分值 做了初始化的缓存 ,代码如下
            private static class LongCache {
            private LongCache(){}
            static final Long cache[] = new Long[-(-128) + 127 + 1];
            static {
                for(int i = 0; i < cache.length; i++)
                    cache[i] = new Long(i - 128);
            }
        }*/
        // 直接声明的Long 验证
        Long a = 5L; Long b = 5L;
        System.out.println("Long与Long 5L 使用 == 结果: " + (a == b)); //true 因为Long 对-128-127 的对象进行了缓存,所以为true
        Long c = 300L; Long d = 300L;
        System.out.println("Long与Long 300L 使用 == 结果: " + (c == d)); // false
        System.out.println("Long与Long 300L 使用 equals 结果:" + (c.equals(d)));// true
        // new 出来的Long 验证结果
        Long newA = new Long(5L); Long newB = new Long(5L);
        System.out.println("Long与Long new 5L 使用 == 结果: " + (newA == (newB)));// false 虽然Long 对127 做了缓存,但是自己new的是新对象 所以==  地址值不一样结果是fasle
        System.out.println("Long与Long new 5L 使用 equals 结果: " + (newA.equals(newB)));// true
        // 如果和int 或long  只要== 中包含基本数据类型,就会自动解包,(不管是直接声明的Long  还是new 的Long)
        Long e = 300L; int f = 300;
        Long g = 300L; long h = 300L;
        Long i = new Long(300);
        System.out.println("Long与int 300 == 结果" + (e == f));//true 会自动转换
        System.out.println("Long与long 300L == 结果" + (g == h));//true 会自动转换
        System.out.println("Long与int 300 equals 结果" + (e == f));//true
        System.out.println("Long与long 300L equals 结果" + (g == h));//true

        System.out.println(" new Long与int 300 == 结果" + (i == f));//true 会自动转换
        System.out.println("new Long与long 300L == 结果" + (i == h));//true 会自动转换


    }

 

本文地址:https://blog.csdn.net/boss_way/article/details/107346126