I am not too new to Java, though I have never really worked with Sets before,
so can anybody please help me out here?
I’m having the following problem;
but first of all, this is my code:
HashMap<Position[], String> save = io.getSave();
Position[][] saved_pos = (Position[][]) save.keySet().toArray();
Though on the second line, Java throws a ClassCastException, but why?
Obviously, the Array returned by save.keySet().toArray() does contain Position[][]s, even though, unfortunately, toArray() in the class Set does only return an Object[] array.
So what can I do, I NEED to cast this.
The
toArray()method doesn’t actually know that it’s being called on a set ofPosition[]s; all it knows is that it’s being called on a set. (This is because of how generics are implemented in Java; not very much information is available at run-time.) So, it just returns anObject[]full ofPartition[]s, rather than returning a truePartition[][]. (The difference being that anObject[]can contain arbitrary objects — it would be valid, after your call, to writesaved_pos[0] = new Object()— whereas a truePartition[][]would raise aArrayStoreExceptionif you tried to set one of its elements tonew Object().)Fortunately, there’s a separate
toArray(...)method that can be used, where you tell it what array type you want, like so: