1. 程式人生 > >JavaSE8基礎 Integer 包裝類對象的值不變

JavaSE8基礎 Integer 包裝類對象的值不變

包裝類 clas () 查看 new like intval ger nts

禮悟:
   好好學習多思考,尊師重道存感恩。葉見尋根三二一,江河湖海同一體。
虛懷若谷良心主,願行無悔給最苦。讀書鍛煉強身心,誠勸且行且珍惜。




javaSE:1.8
os:windows7 x64
ide:MyEclipse 2017



代碼

package jizuiku.demo;

/**
 * Integer 包裝類的對象不能改變其中的值
 * 
 * @author 給最苦
 * @version V17.11.06
 */
public class Demo {
	public static void main(String[] args) {
		// 對象引用 i 變沒變?
		// 有幾個Integer對象?
		Integer i = new Integer(100);

		// 這句話 沒有改變 new Integer(100)所創建的對象 的值嗎?
		i = i + 3;
		System.out.println(i);
	}
}

代碼運行的結果
技術分享

為了知道 包裝類對象的值不變 的原因,給最苦 對上述代碼進行反編譯

// Decompiled by Jad v1.5.8e2. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://kpdus.tripod.com/jad.html
// Decompiler options: packimports(3) fieldsfirst ansi space 
// Source File Name:   Demo.java

package jizuiku.demo;

import java.io.PrintStream;

public class Demo
{

	public Demo()
	{
	}

	public static void main(String args[])
	{
		Integer i = new Integer(100);
		i = Integer.valueOf(i.intValue() + 3);
		System.out.println(i);
	}
}

  (⊙o⊙)…哪裏有新對象呀?沒看到new呀? 這裏就有一個關鍵的函數 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) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

  關鍵的一句: return new Integer(i); 哦,懂了!


學習資源:《Head First Java》+ Xjad + 源代碼 + 清凈的心地。如果您有優秀的書籍,也可以推薦給 給最苦。
博文是看書後,融入思考寫成的。博文好,是書寫得好。博文壞,是 給最苦 沒認真。

JavaSE8基礎 Integer 包裝類對象的值不變