我有一个hashmap<Integer, Card>
Card
是一个类。我已经初始化了hashmap
与 keys
从 0-51,值是 Card
的数组,如下
Card [] card = new Card[52]
for (int i=1; i<=13; i++)
for (int j=0; j<4; j++)
card[++index] = new Card( ((i*10)+j) );
然后我填充 hashmap
如下:
for (int i=1; i<=13; i++)
for (int j=0; j<4; j++)
deck.put( ++key, card[++index] );
现在,我想做的是shuffle
hashmap
的值侧,我不想,举个例子,key[1]对应card[0],key[1]对应card[1]。我想举个例子,key[1] 对应于card[38]。我希望值(value)观方面能够被重新洗牌。我尝试了以下方法:
Collections.shuffle(card,new Random());
但它似乎只接受 ArrayList
和List
。
最佳答案
HashMap 没有可预测的顺序,并且打乱无序的数据结构没有意义。来自 Java 引用文档:
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
如果您使用 0-51 的键,您应该将所有卡片添加到 ArrayList 中。然后你可以使用Collections.shuffle(arrayList)
关于java - 如何使用Java洗牌(尝试使用hashmap,不起作用)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25082619/