java的參考型別的引用所引發的問題

來源:互聯網
上載者:User

標籤:資料   str   集合   記錄   基礎   

看到標題也許感覺有點繞?先看看下面的問題!最近在做Android項目的時候,對一個集合對象的資料的分析怎麼都不對,最後終於發現了問題,來記錄一下,其實超級基礎的東西,╮(╯▽╰)╭

private static ArrayList<Node> mDatas = null;    /**     * @param args     */    public static void main(String[] args) {        ArrayList<Node> a = new ArrayList<Node>();        Node na = new Node();        na.setData(10);        na.setIndex(0);        Node nb = new Node();        nb.setData(11);        nb.setIndex(1);        a.add(na);        a.add(nb);        R(a);// 調用,想一下結果?        R(a);// 再次調用,想想結果?    }    private static void R(ArrayList<Node> a) {        setData(a);        System.out.println("a的資料長度:" + a.size());    }    private static void setData(ArrayList<Node> array) {        if (mDatas != null) {            mDatas.clear();            mDatas = null;        }        mDatas = array;        System.out.println("mData的資料長度:" + mDatas.size());    }

結果是:
mData的資料長度:2
a的資料長度:2
mData的資料長度:0
a的資料長度:0

你對了嗎?

也許對了,那接下來你就不用看了?也許沒對接下來繼續看代碼:
先聲明一個類:

public class Node {    private int data;    private int index;    public int getData() {        return data;    }    public void setData(int data) {        this.data = data;    }    public int getIndex() {        return index;    }    public void setIndex(int index) {        this.index = index;    }}

接下來,看主要代碼:

public static void main(String[] args) {        // TODO Auto-generated method stub        /**         * 集合         */        ArrayList<Integer> a=new ArrayList<Integer>();        Integer i1=1;        Integer i2=2;        a.add(i1);        a.add(i2);        ArrayList<Integer> b=a;        ArrayList<Integer> c=b;        c.clear();        System.out.println("集合的長度:"+a.size());        /**         * 數組         */        int[] in=new int[10];        in[0]=1;        in[1]=2;        int[] ou=in;        ou[0]=0;        System.out.println("數組in的第一個元素:"+in[0]);        System.out.println("數組in第二個元素"+in[1]);        /**         * 自訂對象         */        Node na=new Node();        na.setData(1);        na.setIndex(0);        Node ba=na;        ba.setData(2);        System.out.println("na的data等於:"+na.getData());    }

其實上面的代碼很簡單,就是全部先聲明一個對象,然後再聲明一個該物件類型的變數,再讓其他的變數獲得該對象的引用。例如:b=a,c=b,如果有java基礎應該知道,b或者c獲得的是a這個引用對象的地址,操作b或者c就是直接操作該對象。因此結果:
集合的長度:0
數組in的第一個元素:0
數組in第二個元素2
na的data等於:2

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

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.