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,所以您也可以放入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,而是将String声明为Object类型的实例强制转换为String.

您的问题的解决方案将是以下任何一种:

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

有关更多信息,请参阅 JavadocCollection.toArray(T[] a)

于 2012-08-02T11:24:12.897 回答
3

AObject[]可以添加任何类型的对象。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 回答