jor*_*bor 0 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;
}
Run Code Online (Sandbox Code Playgroud)
而这不是:
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();
Run Code Online (Sandbox Code Playgroud)
该方法toArray()返回一个无法转换为Object[] 实例的实例,String[]就像Object 实例无法转换为String:
// Doesn't work:
String[] strings = (String[]) new Object[0];
// Doesn't work either:
String string = (String) new Object();
Run Code Online (Sandbox Code Playgroud)
但是,因为你可以分配String到Object,你也可以把String进入Object[](这是可能混淆你):
// This works:
Object[] array = new Object[1];
array[0] = "abc";
// ... just like this works, too:
Object o = "abc";
Run Code Online (Sandbox Code Playgroud)
当然,倒数不起作用
String[] array = new String[1];
// Doesn't work:
array[0] = new Object();
Run Code Online (Sandbox Code Playgroud)
当你这样做时(从你的代码):
Set<String> s = configs.keySet();
int g = 0;
for(Object str : s) {
combi[g] = (String) str;
}
Run Code Online (Sandbox Code Playgroud)
你实际上并没有将Object 实例转换为String,你正在将一个String声明为Object类型的实例转换为String.
您的问题的解决方案将是以下任何一个:
String[] combi = configs.keySet().toArray(new String[0]);
String[] combi = configs.keySet().toArray(new String[configs.size()]);
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅Javadoc Collection.toArray(T[] a)