Java - 从hashmap键创建排列 [英] Java - creating permutations from hashmap keys

查看:105
本文介绍了Java - 从hashmap键创建排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个包含键和对象的散列表。我想知道是否可以用键创建一些排列组合。例如,如果我有:

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()); 

然后您可以使用 Collections <

然而,循环的最后一次调用没有任何意义:

  mapPointsShuffle.putAll(mapPoints); 

即使您重新洗牌五十次,这会将相同的地图条目添加到另一张地图因为哈希映射是无序的


是您开始的地图

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?

解决方案

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.

这篇关于Java - 从hashmap键创建排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆