编辑ArrayrList <object>打印不同的结果

时间:2016-05-20 10:11:13

标签: java arraylist

我有一个包含对象Order的ArrayList,其中<​​/ p>

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:不同?

1 个答案:

答案 0 :(得分:0)

如果结果不同,这是正常的。因为您的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变量