有人請向我解釋爲什麼在下面的代碼示例中標記爲//this line gives a compile error (why?)
的行不起作用?爲什麼將一個ArrayList的泛型轉換爲超類不起作用?
import java.util.ArrayList;
public class GenericCastCheck {
class A{
}
class B extends A{
}
public static void main(String[] args) {
A aObject = new A();
B bObject = new B();
//this line works fine
aObject = bObject;
//this line gives a compile (expected)
bObject = aObject;
ArrayList<A> aList = new ArrayList<A>();
ArrayList<B> bList = new ArrayList<B>();
//this line gives a compile error (why?)
aList = bList;
//this line gives a compile error (expected)
bList = aList;
}
}
具體而言,當我們說bList
是ArrayList<B>
型的,它並不意味着它的每一個元素是B
一個實例?如果是這樣,那麼如果我們可以將B
的單個實例投射到A
,那麼將它投射到ArrayList<A>
會出現什麼問題?
謝謝。
非常感謝。我意識到我應該使用'aList = new ArrayList (bList);'而不是'aList = bList',它也編譯得很好。 :) – Animesh 2011-05-18 13:32:23