I am supposed to convert hashes into arrays, but it throws a java.lang.ArrayStoreException at me. I'm taking it one step at a time, trying to see how I can structure it, but it won't run.
Hashes:
{
objectOne : {
attributeOne : 1,
attributeTwo : 2
},
objectTwo : {
attributeOne : 3,
attributeTwo : 4
}
}
into Arrays with structure:
[
{
name : 'objectOne',
attributes : {
attributeOne : 1,
attributeTwo : 2
}
}, {
name : 'objectTwo',
attributes : {
attributeOne : 3,
attributeTwo : 4
}
}
]
My code throws an:
java.lang.ArrayStoreException: java.lang.String
at java.util.AbstractCollection.toArray(AbstractCollection.java:171)
at hashToArray2.main(hashToArray2.java:36)
I've tried to change the parameters to:
Object[] keys = map.keySet().toArray(new Object[map.size()][]));
Object[] values = map.values().toArray(new Object[map.size()][]));
But it yields the same problem.
Code:
public class hashToArray2{
public static void main (String[] args) throws ClassNotFoundException{
Class.forName("hashToArray2");
System.out.println("hashToArray class successfully loaded");
//Creating object1 + input values
HashMap<String, Integer> obj1 = new HashMap<String, Integer>();
obj1.put("attributeOne", 1);
obj1.put("attributeTwo", 2);
//Creating object2 + input values
HashMap<String, Integer> obj2 = new HashMap<String, Integer>();
obj2.put("attributeOne", 3);
obj2.put("attributeTwo", 4);
//Combining obj1+2
//HashMap<String, Integer> map = new HashMap<String, Integer>();
//map.putAll(obj1);
//map.putAll(obj2);
//to array
Object[][] arr1 = new String[obj1.size()][2];
Object[][] arr2 = new String[obj2.size()][2];
//obj1
Object[] keys1 = obj1.keySet().toArray(new Object[obj1.size()][]);
Object[] values1 = obj1.values().toArray(new Object[obj1.size()][]);
for(int i = 0; i < arr1.length; i++){
arr1[i][0] = keys1[i];
arr1[i][1] = values1[i];
}
for(int j = 0; j < arr1.length; j++){
for(int k = 0; k < arr1[j].length; k++){
System.out.println(arr1[j][k]);
}
}
//obj2
Object[] keys2 = obj2.keySet().toArray(new Object[obj2.size()][]);
Object[] values2 = obj2.values().toArray(new Object[obj2.size()][]);
for(int a = 0; a < arr2.length; a++){
arr2[a][0] = keys2[a];
arr2[a][1] = values2[a];
}
for(int b = 0; b < arr2.length; b++){
for(int c = 0; c < arr2[b].length; c++){
System.out.println(arr2[b][c]);
}
}
}
}