我试图让Collections.shuffle()
混洗只有一个数组是使用Collections.nCopies()
生成的3个数组的列表(例如:我只想让它混洗第一个数组,但它最终会混洗列表中的每个数组)以下是我到目前为止所做的工作。我一直试图在Google中查找相同的问题,但提供的唯一示例是字符串或整数,没有数组。
x
为3
,slotType.getSlotitems()
用于阵列["Apple","Cherry","Banana"]
List<ArrayList<String>> q = Collections.nCopies(x,slotType.getSlotitems());
for (ArrayList<String> v : q) {
java.util.Collections.shuffle(v);
System.out.println(v);
System.out.println(q);
}
出现的结果是:
[Cherry, Banana, Apple]
[[Cherry, Banana, Apple], [Cherry, Banana, Apple], [Cherry, Banana, Apple]]
[Cherry, Banana, Apple]
[[Cherry, Banana, Apple], [Cherry, Banana, Apple], [Cherry, Banana, Apple]]
[Cherry, Apple, Banana]
[[Cherry, Apple, Banana], [Cherry, Apple, Banana], [Cherry, Apple, Banana]]
发布于 2020-11-01 16:18:09
nCopies
不会创建您传递给它的元素的副本,因此q
包含一个List
,其中相同的ArrayList<String>
实例重复x
次。当你洗牌其中一个的时候,你就洗牌了所有的(因为实际上只有一个)。
要创建x
不同副本的流,您可以使用List
:
List<ArrayList<String>> q =
IntStream.range(0,x)
.mapToObj(i -> new ArrayList<String>(slotType.getSlotitems()))
.collect(Collectors.toList());
现在shuffle
只会影响其中一个ArrayList
。
另一种选择:
List<ArrayList<String>> q =
Collections.nCopies(x,slotType.getSlotitems())
.stream()
.map(ArrayList::new)
.collect(Collectors.toList());
在这里,我获取了原始的List<ArrayList<String>>
(其中所有元素都是相同的实例)并创建了一个新的List<ArrayList<String>>
,其中每个元素都是原始元素的副本。
https://stackoverflow.com/questions/64629830
复制相似问题