2017-06-17 58 views
2

印刷可能有人請解釋一下我爲什麼我得到這個輸出我不知道爲什麼A的對象也越來越在最後

package code; 
import java.util.ArrayList; 
class A { 
} 
class B extends A { 
}  
class C extends B { 
} 
public class ThreadDemo { 
    public static void main(String[] args) { 
     ArrayList<A> x = new ArrayList<A>(); 
     ArrayList a = new ArrayList(); 
     x.add(new A()); 
     a = x; 
     a.add(new B()); 
     ArrayList b = a; 
     ArrayList<C> c = (ArrayList<C>) b; 
     c.add(new C()); 
     a.add(new A()); // I am not sure why object of A is also getting printed at the last 
     for (Object obj : c) { 
      System.out.println(obj + " class Name " + obj.getClass().getName()); 
     } 
    } 
} 

輸出:

---------- 
[email protected] class Name code.A 
---------- 
[email protected] class Name code.B 
---------- 
[email protected] class Name code.C 
---------- 
[email protected] class Name code.A 
---------- 
+1

我越來越糊塗與輸出lastLine所 –

+2

你只是* *創建兩個'ArrayList'實例,並從'ArrayList的一個新= ArrayList中的第二個();'從不使用,因爲它被丟棄了兩行,而'a'的值被替換。之後,'x','a','b'和'c'都引用了* same *'ArrayList'對象。 – Andreas

+0

如果這不是你期望的輸出,你會期望什麼*,爲什麼? –

回答

1

因爲當你使用b=a你只是保存對b的引用。無論你申請的變化是否也會影響b。而且由於你做了c=b那麼c也會受到影響。您不保存列表的副本,然後更改其中一個的值,而是保存對b和c中的一個引用。

所以,當你在最後使用a.add(),它被添加到b和c太

2

ac是同一個對象。讓我們來看看代碼的相關線路:

ArrayList a = new ArrayList(); // a is created 
ArrayList b = a; // b holds a reference to the same object 
ArrayList<C> c = (ArrayList<C>) b; // and so does c 

所以每當你對象添加到c,它會出現在a過(因爲,如前所述,它們是同一個對象!)。

+0

我對上述程序中的評論部分 –

+0

@VedPrakash感到困惑哦,我誤解了這個問題。看到我編輯的答案。 – Mureinik

+1

因爲'c'和'a'引用同一個對象。 –

1

在你的代碼有ArrayList中的4個引用:X,A,B和C。

您最初有2個ArrayList對象,其中a作爲參考,x作爲另一個的參考。但a = x使得最初由a引用的ArrayList的對象符合垃圾回收的條件。現在,ax都指向同一個ArrayList,並且您已經添加了A的對象。因此ArrayList有[A]

接下來給它添加一個B的對象,這樣arrayList的狀態是[A,B]ax均指這個列表。 接下來,您將創建另一個參考b,並使其也引用由a所引用的對象,因此您現在有a,b,x指的是相同的列表。

接下來,您將創建另一個參考c並使其與b所指的相同對象相同,因此現在您有4個引用引用同一列表。列表的狀態是[A,B]

現在您使用參考c在列表中添加C的對象,然後使用參考a添加對象A。由於所有4個引用都指向同一個ArrayList,因此AB的對象都被添加到列表和列表的狀態:[A,B,C,A]

現在,當你迭代列表和System.out.println()使用參考打印時,toString()方法被調用,當你從Object.java derieved被調用沒有重寫它因此方法。

您的問題的答案,爲什麼A的對象在最後打印? :因爲列表在最後包含它,如上所述。希望能幫助到你。

+0

'a = x' does not not **使ArrayList最初被'x'引用的對象符合垃圾回收的條件。 – Andreas

+0

哎呀對不起,我的意思是由'a'引用的數組列表,謝謝您的糾正 –

+0

我改正了,我現在可以讓-1恢復原狀:) –

1

您將第一個ArrayList對象分配給所有ArrayList參考。

ArrayList<A> x = new ArrayList<A>(); 
ArrayList a = new ArrayList(); 
//x.add(new A()); 
a = x; //now a & x refer to same object. 
//a.add(new B()); 
ArrayList b = a; //b refer to the same object. 
ArrayList<C> c = (ArrayList<C>) b; //now a,b,x & c every reference refer the same object. 

因此,您在整個代碼中將元素分配到相同的ArrayList

希望這將是有益的......