So I have a hashmap that has keys and objects. I was wondering if it was possible to create a number of permutations with the keys. So for example if i had:
1 - Object1
2 - Object2
3 - Object3
4 - Object4
To get a random order. So one outcome may be:
3 - Object3
1 - Object1
2 - Object2
4 - Object4
So far i have:
Map<Integer, GeoPoint> mapPoints = new HashMap<Integer, GeoPoint>();
Map<Integer, GeoPoint> mapPointsShuffle = new HashMap<Integer, GeoPoint>();
for (int t =0; t < 50; t ++){
Collections.shuffle((List<?>) mapPoints);
mapPointsShuffle.putAll(mapPoints);
}
So the idea is to give me 50 random permutations. But it comes back with :
09-26 11:15:27.813: E/AndroidRuntime(20434): java.lang.ClassCastException: java.util.HashMap cannot be cast to java.util.List
Any ideas?
java.util.HashMap does not implement java.util.List
You should make a list from hashmap keys first:
List<Integer> keys = new List<Integer>(mapPoints.keySet());
Then you can shuffle the key list using the method in the Collections
the way your post shows.
The last call of your loop makes no sense, however:
mapPointsShuffle.putAll(mapPoints);
Even if you re-shuffle the keys fifty times, this would add the same map entries to another map fifty times over, resulting in the map with which you have started, because hash maps are unordered.
This link guides you in how to generate a list from a hashmap, get this instead of trying to shuffle the hashmap!!
How can you cast a map to list?
Collections.shuffle((List) mapPoints);
Are you trying to shuffle the keys? For HashMap you can't predict the order in which keys will be returned. So, you better get the keys in a list and then shuffle.