对象共享池中

    @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)
    }
相关文章
相关标签/搜索