编辑数组列表<Object>打印不同的结果



我有一个 ArrayList,其中Order对象

public class Order{
    private String product;
    private String version;   
    ArrayList<String> availableVersions;    
    //etc..
}

一开始,物体就像Order o = new Order ("product1", "01");.因此,我想将所有对象分组为具有相同的产品名称,并组合可能具有的所有不同版本。我已经做到了:

//ArrayList<Order> labels contains data with o objects.
for(Order o:labels){
    System.out.println("1: product " + o.getProduct() + " has versions " + o.getVersion());
}
ArrayList<Order> temp = new ArrayList<>();
ArrayList<String> versions = new ArrayList<>();
String product;
for(Order o:labels){    
    product = o.getProduct(); //store the name of product to compare it with the list in the following loop.
    temp.clear();
    versions.clear();   
    for(Order o1:labels){
        if(product.equals(o1.getProduct())){ //collect all the object with the same product name in a temporary list.
            temp.add(o1); 
        }
    }
    for(Order lb:temp){ //iterate the list and get the version of each element
        versions.add(lb.getVersion());               
    }
    o.setAvailableVersions(versions); //add the list with all the versions in the current object.
    System.out.println("2: product " + o.getProduct() + " has versionss " + o.getAvailableVersions());
}
for(Order o:labels){
    System.out.println("3: product " + o.getProduct() + " has versionss " + o.getAvailableVersions());
}

我得到

1: product 25043625 has versionss 01
1: product 25043625 has versionss 02
2: product 25043625 has versionss [01, 02]
2: product 25043625 has versionss [01, 02]
3: product 25043625 has versionss [01]
3: product 25043625 has versionss [01]

为什么????我打印相同的对象?为什么输出2:3:不同?

如果结果不同,这是正常的。因为您的versions变量在任何地方都具有相同的引用。每次进入循环时,您仍在修改与上一次迭代相同的versions列表,从而更改以前的值。如果你想修复它,你需要像这样在for循环中初始化它

ArrayList<Order> temp = new ArrayList<>();
ArrayList<String> versions;
String product;
for(Order o:labels){
    product = o.getProduct(); //store the name of product to compare it with the list in the following loop.
    temp.clear();
    versions = new ArrayList<>();
    // The rest of your code
}

希望它能帮助你

优化

您可以优化代码并更改此部分:

for(Order o1:labels){
    if(product.equals(o1.getProduct())){ //collect all the object with the same product name in a temporary list.
        temp.add(o1); 
    }
}
for(Order lb:temp){ //iterate the list and get the version of each element
    versions.add(lb.getVersion());               
}

对此

for(Order o1:labels){
    if(product.equals(o1.getProduct())){ //collect all the object with the same product name in a temporary list.
        versions.add(o1.getVersion());
    }
}

然后摆脱temp变量

最新更新