Reputation: 2232
why does this run:
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;
}
and this not:
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();
Upvotes: 0
Views: 97
Reputation: 220842
The method toArray()
returns an Object[]
instance, which cannot be cast to String[]
, just like an Object
instance cannot be cast to String
:
// Doesn't work:
String[] strings = (String[]) new Object[0];
// Doesn't work either:
String string = (String) new Object();
However, because you can assign String
to Object
, you can also put String
into Object[]
(which is what probably confuses you):
// This works:
Object[] array = new Object[1];
array[0] = "abc";
// ... just like this works, too:
Object o = "abc";
The inverse wouldn't work, of course
String[] array = new String[1];
// Doesn't work:
array[0] = new Object();
When you do this (from your code):
Set<String> s = configs.keySet();
int g = 0;
for(Object str : s) {
combi[g] = (String) str;
}
You're not actually casting an Object
instance to String
, you're casting a String
instance declared as an Object
type to String
.
The solution to your problem would be any of these:
String[] combi = configs.keySet().toArray(new String[0]);
String[] combi = configs.keySet().toArray(new String[configs.size()]);
Refer to the Javadoc for more info about Collection.toArray(T[] a)
Upvotes: 8
Reputation: 533492
A Object[]
can have any type of object added to it. A String[]
can only contains Strings or null
If you could cast the way you suggest, you would be able to do.
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?
Upvotes: 3