对象共享池中

    @Test
    public void testName() throws Exception {
        // 手动创建
        Short s1 = new Short((short) 129);
        Short s2 = new Short((short) 129);
        System.out.println(s1 == s2); // false

        Short s3 = new Short((short) 126);
        Short s4 = new Short((short) 126);
        System.out.println(s3 == s4); // false

        /*
         * 结论:
         * 每次手动创建,都会创建一个新的对象。手动new的对象,地址是肯定不会相同的。
         * 
         * 自动装箱的对象,地址可能会相同,即可能会重用对象共享池中的对象。仅限常用少量的数据(范围:-128<= x <= 127)。
         * 数值较大的数据,在自动装箱时,依然会创建一个新的对象。
         */

        // 自动装箱
        Short s11 = (short) 129;
        Short s22 = (short) 129;
        System.out.println(s11 == s22); // false

        Short s33 = (short) 126;
        Short s44 = (short) 126;
        System.out.println(s33 == s44); // true,享元模式,有个共享池,存放常用少量的数据(范围:-128<= x <= 127)
    }
原文地址:https://www.cnblogs.com/zj0208/p/8033085.html