關於java中的“引用”概念

來源:互聯網
上載者:User

標籤:方式   java編程思想   按值傳遞   值傳遞   generated   test   void   因此   基本資料   

前言

最近在閱讀《java編程思想》一書時,對作者關於java中的”引用(控制代碼)“的解釋不太清楚,因此以實驗的方式來討論下java中一切皆”按值傳遞“這一說法,從而加深理解。

本文情景一:當參數為基礎資料型別 (Elementary Data Type)(如:int)時
public class TestReference {    public static void testOne(int i){        i = 2;        System.out.println("test函數中的變數值:" + i);    }    public static void main(String[] args) {        // TODO Auto-generated method stub        int a = 1;        TestReference.testOne(a);        System.out.println("main函數中的變數值:" + a);    }}

運行結果:
test函數中的變數值:2
main函數中的變數值:1
由此可見:當參數為基礎資料型別 (Elementary Data Type)時,參數的傳遞為按值的拷貝傳遞

情景二:當參數為對象時,出現“按引用傳遞”的效果
package test;public class TestReference {    public static void testTwo(B c){        c.data = 2;        System.out.println("test函數中的變數值:" + c.data);    }    public static void main(String[] args) {        // TODO Auto-generated method stub        B b = new B();        b.data = 1;        TestReference.testTwo(b);        System.out.println("main函數中的變數值:" + b.data);    }}

運行結果:
test函數中的變數值:2
main函數中的變數值:2
由此可見:此例中函數的參數確實以拷貝地址的方式操作了實參變數。

情景三: 函數中對參數建立新的對象
public class TestReference {    public static void testThree(String str){        str = new String("new");        System.out.println("test函數中的變數值:" + str);    }    public static void main(String[] args) {        // TODO Auto-generated method stub        String str = new String("old");        TestReference.testThree(str);        System.out.println("main函數中的變數值:" + str);    }}

運行結果:
test函數中的變數值:new
main函數中的變數值:old
由此可見:實參變數以拷貝地址的方式將對象地址傳遞給了形參變數,但在函數運行過程中,形參變數被賦予的新的對象的地址,因此此後對形參變數的操作與實參變數便不再有關係。

總結

所謂“一切皆傳值”對於基礎資料型別 (Elementary Data Type),指的便是變數值得拷貝,而對於對象(或String、Integer等封裝基本類型),指的是對象地址的拷貝,也就是說所傳遞的值是對象的地址。

關於java中的“引用”概念

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.