Java - 从hashmap键创建排列 [英] Java - creating permutations from hashmap keys
问题描述
1 - Object1
2 - Object2
3 - Object3
4 - Object4
获得随机订单。所以一个结果可能是:
$ b $ 3 - Object3
1 - Object1
2 - Object2
4 - Object4
到目前为止,我有:
Map< Integer,GeoPoint> mapPoints = new HashMap< Integer,GeoPoint>();
Map< Integer,GeoPoint> mapPointsShuffle = new HashMap< Integer,GeoPoint>(); (int t = 0; t <50; t ++){
Collections.shuffle((List<> mapPoints);
mapPointsShuffle.putAll(mapPoints);
}
所以这个想法是给我50个随机排列。但它回来了:
09-26 11:15:27.813:E / AndroidRuntime(20434):java.lang.ClassCastException:java.util.HashMap不能强制转换为java.util.List
有什么想法?
您应该首先使用hashmap键创建一个列表:
List< Integer> keys = new List< Integer>(mapPoints.keySet());
然后您可以使用 然而,循环的最后一次调用没有任何意义: 即使您重新洗牌五十次,这会将相同的地图条目添加到另一张地图因为哈希映射是无序的。 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: 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? You should make a list from hashmap keys first: Then you can shuffle the key list using the method in the The last call of your loop makes no sense, however: 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. 这篇关于Java - 从hashmap键创建排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! Collections <
mapPointsShuffle.putAll(mapPoints);
是您开始的地图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);
}
List<Integer> keys = new List<Integer>(mapPoints.keySet());
Collections
the way your post shows.mapPointsShuffle.putAll(mapPoints);