• 【Java基础】Integer包装类的缓冲池问题


    首先看下面这个例子:

    public class TestNew {
        public static void main(String args[]){
            Integer i1 = 10;
            //Integer i1 = Integer.valueOf(10);
            Integer i2 = 10;
            Integer i3 = 1000;
            Integer i4 = 1000;
            System.out.println(i1 == i2);
            System.out.println(i3 == i4);
        }
    }

    其中注释的地方是用来表示编译器优化后代码的样子,说明应该对于i1 = 10的赋值,由于是包装类,所以要创建一个Integer对象,这样,最后两个对象的地址比较,肯定结果都是false,但是真实的结果并不是这样。

    true
    false
    
    Process finished with exit code 0

    第一个比较的结果竟然是true,为了弄清楚原因,就要看Integer的valueOf方法的具体实现了。

       /**
         * Returns an {@code Integer} instance representing the specified
         * {@code int} value.  If a new {@code Integer} instance is not
         * required, this method should generally be used in preference to
         * the constructor {@link #Integer(int)}, as this method is likely
         * to yield significantly better space and time performance by
         * caching frequently requested values.
         *
         * This method will always cache values in the range -128 to 127,
         * inclusive, and may cache other values outside of this range.
         *
         * @param  i an {@code int} value.
         * @return an {@code Integer} instance representing {@code i}.
         * @since  1.5
         */
        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);
        }

    从这里可以看出,对于value在-128到127之间的int值,在调用这个方法创建Integer对象时,是直接从缓冲池中返回的,如果缓冲池中有,则返回的是同一个对象。

    那如果此时,对i2赋值为1,是否i1也会变为1呢?

    答案是否定的,上一篇文章中的包装类的参数传递问题和这个类似,因为将1赋值给i2,这时候1被自动装箱为Integer对象,并让i2指向这个新对象,所以此时不会改变i

    的值。

  • 相关阅读:
    《House of Cards》观后感
    几个常见的壳的脱壳
    【转】Arp的攻防实战
    Back Track 5 之 漏洞攻击 && 密码攻击 && Windows下渗透工具
    Back Track 5 之 Web踩点 && 网络漏洞
    Back Track 5 之 网络踩点(二)
    Back Track 5 之 网络踩点
    51单片机总线与非总线的程序对比
    关于PHP写的投票网站之刷票终结版
    关于PowerShell中的命令的别名
  • 原文地址:https://www.cnblogs.com/gslyyq/p/4950848.html
Copyright © 2020-2023  润新知