java循环的奇怪行为

java循环的奇怪行为,java,loops,shuffle,Java,Loops,Shuffle,我得到的结果是: Inside loop : [5, 6, 3, 1, 4, 2] Inside loop : [3, 1, 5, 6, 4, 2] Inside loop : [1, 2, 4, 5, 6, 3] Inside loop : [5, 2, 6, 4, 3, 1] Outside loop : [5, 2, 6, 4, 3, 1] Outside loop : [5, 2, 6, 4, 3, 1] Outside loop : [5, 2, 6, 4, 3, 1]

我得到的结果是:

Inside loop : [5, 6, 3, 1, 4, 2]

Inside loop : [3, 1, 5, 6, 4, 2]

Inside loop : [1, 2, 4, 5, 6, 3]

Inside loop : [5, 2, 6, 4, 3, 1]

Outside loop : [5, 2, 6, 4, 3, 1]

Outside loop : [5, 2, 6, 4, 3, 1]

Outside loop : [5, 2, 6, 4, 3, 1]

Outside loop : [5, 2, 6, 4, 3, 1]
代码:

import java.util.ArrayList;
导入java.util.List;
导入java.util.Random;
公共类可能解{
//在何处放置切口以划定路线的索引(不同
//(车辆)
int[]指示切口;
//每个路线的已订购客户集。由切割分隔的路线
ArrayList OrderedCustomers;
//数组长度
整数大小;
//建造师
公共可能解决方案(int[]索引,ArrayList客户){
this.indicatescut=指数;
this.OrderedCustomers=客户;
this.size=Customers.size();
}
//方法生成一个可能解的邻域。我们需要一个
//参数
//指定要生成的邻居数的步骤
公共可能的解决方案[]Genereneighborhood(整数){
可能的解决方案[]溶胶=新的可能的解决方案[编号];
for(int i=0;i
您所有的
可能的解决方案
s都引用相同的
阵列列表


(所有
ArrayList
变量和字段都指向在
main()
中创建的单个
ArrayList
。因此,每次洗牌列表时,都会影响列表中的所有值。如果希望
PossibleSolution()
要捕获调用列表时列表状态的快照,您需要制作一份副本。)

标记为“外部循环”的所有打印语句始终在同一数组上执行。在退出第一个
for
循环后,您不再随机化任何内容。您只是一次又一次地打印。

Summary 构造函数不复制客户,它只存储对客户的引用。同样,如果您将一个对象的引用传递给多个
可能的解决方案
s,那么它们都将共享该解决方案

public PossibleSolution(int[]indices, ArrayList<Integer> Customers){
    this.indicesCut = indices;
    this.OrderedCustomers = Customers; //<-- Only the reference is copied, not the object

    this.size = Customers.size();
}
因为它与订购的客户相同

解决方案 如果您想要一份副本,那么您需要请求对象的副本,而不仅仅是引用,最简单的方法是使用:

进一步阅读 可以找到相同“在不同地方引用相同对象”问题的简化版本


其他注释
OrderedCustomers
Customers
都是变量,因此它们应该是较低的<代码>订购客户
客户

问题是什么?代码应该做什么?您能解释一下您对输出的期望吗?要展开,OP需要在其可能的解析构造函数中使用.clone()或Collections.copy方法,以便它们引用不同的数据结构。
public PossibleSolution(int[]indices, ArrayList<Integer> Customers){
    this.indicesCut = indices;
    this.OrderedCustomers = Customers; //<-- Only the reference is copied, not the object

    this.size = Customers.size();
}
for(int i =0; i<number;i++){        
        java.util.Collections.shuffle(this.OrderedCustomers);

        sol[i] = new PossibleSolution(this.indicesCut,this.OrderedCustomers);
        System.out.println("Inside loop : "+sol[i].OrderedCustomers);
    }
for(int i=0; i<number;i++){
   System.out.println("Outside loop : "+sol[i].OrderedCustomers);
}
System.arraycopy(from, 0,to,0,from.length);