Java 物件的轉型

Given:
11. public static void main(String[] args) {

12. Object obj = new int{1, 2, 3};
13. int[] someArray = (int[])obj;
14. for (int i: someArray) System.out.print(i + " ");
15. }
What is the result?
A. 1 2 3
B. Compilation fails because of an error in line 12.
C. Compilation fails because of an error in line 13.
D. Compilation fails because of an error in line 14.
E. A ClassCastException is thrown at runtime.
答案:A
參考:7-8 物件的轉型

今天一直在想這個SCJP 6.0 認證教戰手冊書裡的77題為什麼答案會是A啊?Object obj = new int{1,2,3}在Eclipse一直提示Syntax error on token "int", Dimensions expected after this token這樣的錯誤,但是我一直也搞不懂哪裡錯,就是覺得怪怪的,後來Google之後,才警覺原來是要Object obj = new int[]{1,2,3}啦!少了一對中括號,誤會很大說!

感謝你看到這裡,很快就可以離開了,但最好的獎勵行動就是按一下幫我分享或留言,感恩喔~

點我分享到Facebook

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *