0

なぜこれが実行されるのですか:

    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();
4

2 に答える 2

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に入れることもできますString(Object[]おそらく混乱するでしょう)。

// 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キャストしています。StringObjectString

問題の解決策は次のいずれかです。

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

詳細については、Javadoc を参照してください。Collection.toArray(T[] a)

于 2012-08-02T11:24:12.897 に答える
3

Object[]は、任意のタイプのオブジェクトを追加できます。AString[]には文字列のみを含めるか、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?
于 2012-08-02T11:28:31.537 に答える