Object[]陣列與String[]陣列轉換問題
阿新 • • 發佈:2019-01-06
在一本書中看到Object[] 與 String[] 的轉換。發現有點很奇怪
Object[] ob = {"hello","World"};
String[] str = (String[]) ob;
//報異常Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String]
原因是Object[] 陣列不能強轉成String[]陣列;
Object[] object = {"ss","sssss"}; System.out.println(object.getClass()); //輸出結果:class [Ljava.lang.Object; for(Object o : s) { System.out.println(o.getClass()); } //輸出結果:class java.lang.String Object[] object = new String[10]; System.out.println(object.getClass()); //輸出是:class [Ljava.lang.String;