为什么我们不能从Object []转换为String [],而我们可以从数组中的值?
问题描述:
为什么这样运行:为什么我们不能从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();
答
toArray()
返回Object[]
实例,不能转换为String[]
,就像一个Object
实例不能在方法投到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
,你铸造声明为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)
答
一个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
除了你可以绕过类型擦除的编译器检查外,你对'列表
+1显示海报需要的代码 – dsh 2012-08-02 11:38:21
我想我现在看到它谢谢! – jorrebor 2012-08-02 13:02:43