为什么我们不能从Object []转换为String [],而我们可以从数组中的值转换?

时间:2012-08-02 11:21:56

标签: java arrays casting

为什么会这样:

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

2 个答案:

答案 0 :(得分:8)

方法toArray()会返回Object[] 实例,无法转换为String[],就像Object 实例< / em>无法转换为String

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

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

但是,因为您可以将String分配给Object,您还可以将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 实例,而是投放了String个实例,声明为Object类型到String

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

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

有关Collection.toArray(T[] a)

的更多信息,请参阅Javadoc

答案 1 :(得分: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?