-4

我正在尝试创建一个哈希映射的排列,该映射将键作为键并以随机顺序多次对其进行洗牌,但保留相同的对象。

到目前为止,我有:

Map<Integer, GeoPoint> mapPoints = new HashMap<Integer, GeoPoint>();
ArrayList<Integer> keys2 = new ArrayList<Integer>(mapPoints.keySet());

for (int t =0; t < 50; t ++){

            Collections.shuffle(keys2);

        }

但据我所知,它并没有改变它们。谁能看到我做错了什么。

4

1 回答 1

2

What does "shuffled" look like to you? There's no order for keys in HashMap. You need a LinkedHashMap to preserve insertion order.

Shuffling the Collection of keys won't affect the Map per se; you iterate over it to access the Map keys.

See if this gives you a different ordering after you run it.

Map<Integer, GeoPoint> mapPoints = new HashMap<Integer, GeoPoint>();
System.out.println("before shuffle ");
Set<Integer> keys = mapPoints.keySet();
for (int key : keys) {
    System.out.println("key : " + key + " value: " + mapPoints.get(key));
}
Collections.shuffle(keys);  // don't know why multiple shuffles are required.  deck of cards?
System.out.println("after shuffle ");
for (int key : keys) {
    System.out.println("key : " + key + " value: " + mapPoints.get(key));
}
于 2012-09-26T12:22:45.850 回答