【发布时间】:2016-08-01 10:41:32
【问题描述】:
魔法之后
System.out.println("*****");
Collections.shuffle(a);
~$ java -version java版本“1.8.0_101” Java(TM) SE 运行时环境 (build 1.8.0_101-b13) Java HotSpot(TM) 64 位服务器 VM(内部版本 25.101-b13,混合模式)
public static void main(String[] args) {
List<Integer> a = Arrays.asList(1, 3, 5, 9, 14);
Collections.shuffle(a);
System.out.println(a);
List<Integer> b = a.subList(0, a.size() - 1);
List<Integer> b1 = new ArrayList<>(a.subList(0, a.size() - 1));
System.out.println(b);
System.out.println(b1);
System.out.println("*****");
Collections.shuffle(a);
System.out.println(a);
Collections.shuffle(b);
System.out.println(b);
Collections.shuffle(b1);
System.out.println(b1);
}
[14, 1, 9, 3, 5]
[14, 1, 9, 3]
[14, 1, 9, 3]
*****
[14, 9, 3, 5, 1]
[3, 14, 9, 5]
[1, 14, 9, 3]
shuffle(a) 之后的 b 不是 a.subList(0, a.size() - 1) 之后的 eq b; \
更新
是的!一步步! 1) 创建 a 2) 创建 b 子列表 a 3) shuffle(a) 为什么 shuffle(a) 修改 b ?
更新 2
为什么是正确的?为什么当我 shuffle b 我改变 a 的顺序时这是真的?
public static void main(String[] args) {
List<Integer> a = Arrays.asList(1, 3, 5, 9, 14);
Collections.shuffle(a);
System.out.println(a);
List<Integer> b = a.subList(0, a.size() - 1);
System.out.println(b);
System.out.println("*****");
Collections.shuffle(b);
System.out.println(a);
System.exit(0);
}
[1, 9, 3, 5, 14]
[1, 9, 3, 5]
*****
[3, 9, 5, 1, 14]
【问题讨论】:
-
我真的不太清楚你的意思 - 你的最后一句话没有准确地解释你的期望或更重要的是为什么你期望它。
-
到底是什么问题?你想知道为什么洗牌实际上是洗牌集合吗?我的意思是......这是它应该做的......
-
您似乎有三个独立的列表,并且您分别对每个列表进行了洗牌。
-
其实它们并不是独立的。
b是a的子列表,因此它由同一个 ArrayList 实例支持。 -
请注意,您在打印之前将
b和b1改组,因此即使if 它们会保留a的相同顺序,那么它们将以不同的顺序打印洗牌后。