2011-04-11 132 views
2
class Dims { 
    public static void main(String[] args) { 
     int[][] a = {{1,2,}, {3,4}}; 
     int[] b = (int[]) a[1]; 
     Object o1 = a; 
     int[][] a2 = (int[][]) o1; 
     int[] b2 = (int[]) o1; // Line 7 
     System.out.println(b[1]); 
    } 
} 

我對上面的Java代碼有疑問。
爲什麼它會在第7行給出運行時異常而不是編譯時錯誤?編譯時間和運行時錯誤

+1

您有問題,或者您的家庭作業有問題? – 2011-04-11 18:48:18

+0

這是我正在閱讀的Java書中的一個問題。這本書也有解決方案。 – Student 2011-04-11 18:52:05

回答

4

因爲o1是一個int [] [],而不是int []。你得到的RuntimeException是一個ClassCastException,因爲第一個是int數組的數組,而後者只是一個int數組。

您不會收到編譯時錯誤,因爲o1被定義爲Object。所以在編譯時,它可以包含從object派生的任何東西,事實上除了基本類型long,int,short,byte,char,double,float和boolean之外,其實都是Java中的所有類型。所以,在編譯時,這個對象似乎可能實際上是一個int []。

3

您不能通過強制轉換將二維數組轉換爲一維數組。您需要以某種方式將值複製到新的一維數組中。

1

無論您何時不使用強制轉換,編譯器都可以確定該使用是否有效。如果你使用了一個強制轉換,你告訴編譯器你知道你在做什麼,它必須使用不同的類型作爲參考。

int[][] a = {{1, 2,}, {3, 4}}; 
int[] b = a[1]; // no cast is used here and the compiler can tell this is valid. 
Object o1 = a; 
int[][] a2 = (int[][]) o1; // This cast is fine. 
int[] b2 = (int[]) o1; // My IDE warns this case may produce a ClassCastException. 
System.out.println(b[1]);