java - 以随机顺序对arraylist进行排序

标签 java arraylist collections

我正在编写纸牌游戏,我有一个 ArrayList 持有纸牌(Object),其中 他们每个人都有自己的 ID。

因为我想让这个游戏支持多人模式, 我必须以某种方式在 2 名玩家之间发送/接收游戏进度。

现在,如果我在一边洗牌,我必须在另一边做同样的事情,但要发送的数据包会很大,因为每张牌都有图像。

我想的是发送一个打乱后的列表的整数数组,所以它会在另一边收到并按照整数数组重新排序。

如何发送打乱的订单并应用到另一边?

最佳答案

Random类可以用于此。

If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers. In order to guarantee this property, particular algorithms are specified for the class Random. Java implementations must use all the algorithms shown here for the class Random, for the sake of absolute portability of Java code.

这意味着您可以只将种子值传输到客户端,使用它实例化一个新的 Random 实例,并期望接收到与其他玩家机器上相同的随机数序列。

Collections.shuffle可以使用 Random 源调用。

关于java - 以随机顺序对arraylist进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47200129/

相关文章:

java - 替换java中的字符序列

java - 按钮单击 onListener 并转到不同的 xml 布局

java - 我可以在 .removeif() 中使用 .size() 作为 ArrayList 的条件吗?

Java -- MongoDB collection.find() by _id

java - 实现 CharSequence 以便使用 String.join?

java - 正则表达式,如何在第一次失败时中止?

java - 使用自定义对象数组

java - arrayList中一一保存文件信息

java - indexOf() 方法在 ArrayList 中找不到我的字符串

c# - .NET 中是否有任何集合可以防止空条目?