2012-08-02 77 views
0

爲什麼這樣運行:爲什麼我們不能從Object []轉換爲String [],而我們可以從數組中的值?

static TreeMap<String, int[]> configs = new TreeMap<String, int[]>(); 

    int[] upperarms_body = {2,3,4,6}; 
    int[] left_arm = {1,2}; 
    int[] right_arm = {6,7}; 
    int[] right_side = {5,6,7}; 
    int[] head_sternum = {3,4}; 


    configs.put("upperarms_body", upperarms_body); 
    configs.put("left_arm", left_arm); 
    configs.put("right_arm", right_arm); 
    configs.put("right_side", right_side); 
    configs.put("head_sternum", head_sternum); 



    // create a config counter 
    String[] combi = new String[configs.keySet().size()]; 

    Set<String> s = configs.keySet(); 
    int g = 0; 
    for(Object str : s){ 
     combi[g] = (String) str; 
    } 

,這不:

static TreeMap<String, int[]> configs = new TreeMap<String, int[]>(); 

    int[] upperarms_body = {2,3,4,6}; 
    int[] left_arm = {1,2}; 
    int[] right_arm = {6,7}; 
    int[] right_side = {5,6,7}; 
    int[] head_sternum = {3,4}; 

    configs.put("upperarms_body", upperarms_body); 
    configs.put("left_arm", left_arm); 
    configs.put("right_arm", right_arm); 
    configs.put("right_side", right_side); 
    configs.put("head_sternum", head_sternum); 



    //get an array of thekeys which are strings 
    String[] combi = (String[]) configs.keySet().toArray(); 

回答

8

toArray()返回Object[]實例,不能轉換爲String[],就像一個Object實例不能在方法投到String

// Doesn't work: 
String[] strings = (String[]) new Object[0]; 

// Doesn't work either: 
String string = (String) new Object(); 

但是,因爲您可以分配給StringObject,你也可以把StringObject[](這是可能混淆你):

// This works: 
Object[] array = new Object[1]; 
array[0] = "abc"; 

// ... just like this works, too: 
Object o = "abc"; 

逆是行不通的,當然

String[] array = new String[1]; 
// Doesn't work: 
array[0] = new Object(); 

當你做到這一點(從代碼中):

Set<String> s = configs.keySet(); 
int g = 0; 
for(Object str : s) { 
    combi[g] = (String) str; 
} 

您實際上並不投Object實例String,你鑄造聲明爲Object類型String一個String實例。

你的問題的解決方案將是任何這些:

String[] combi = configs.keySet().toArray(new String[0]); 
String[] combi = configs.keySet().toArray(new String[configs.size()]); 

參考JavaDoc以獲得更多信息關於Collection.toArray(T[] a)

+0

+1顯示海報需要的代碼 – dsh 2012-08-02 11:38:21

+0

我想我現在看到它謝謝! – jorrebor 2012-08-02 13:02:43

3

一個Object[]可以有任何類型的對象添加到它。一個String[]只能包含字符串或null

如果你能投你建議的方式,你就能夠做到。

Object[] objects = new Object[1]; 
String[] strings = (String[]) objects; // won't compile. 
objects[0] = new Thread(); // put an object in the array. 
strings[0] is a Thread, or a String? 
+0

+1解釋'爲什麼'。 – dsh 2012-08-02 11:36:46

+0

除了你可以繞過類型擦除的編譯器檢查外,你對'列表'和'列表'有同樣的問題。 – 2012-08-02 11:38:17

相關問題