ArrayList clear从其他ArrayLists中删除对象属性

时间:2017-06-14 04:40:28

标签: java arraylist

对象代码

public class Example{
    private ArrayList<Point> points;

    public Example(ArrayList<Point> points)
       this.points = points;
    }
    //get and set here
}

全球代码

 public static ArrayList<Example> examples = new ArrayList<>();

主要代码

private ArrayList<Point> points = new ArrayList<>();

private void addPoints(){
   this.points.add(new Point(num1,num2));
   //some more adds
}

private void newObject(){
   Global.examples.add(new Example(this.points));
   this.points.clear();
}

致电代码:

try {
    Global.vehicles.add(new Car((int)Math.random()*1+5,0.3,this.actualPoints.get(0).getX‌​(),this.actualPoints‌​.get(0).getY(),getCo‌​lor(),this.actualPoi‌​nts,"east","Car",nul‌​l,null,new VehicleBuffer()));
} catch (IOException ex) {
}
this.actualPoints.clear();

因此每当我向Example ArrayList添加一个新对象时,它会删除所有对象的ArrayList,以及打印所有对象的toString,如果我不使用,则显示所有对象的相同值明确的命令,他们不应该有他们自己的个人ArrayList点而不是使用相同的?它确实与Example ArrayList是静态的吗?因为我需要从其他对象获取值而不使用它们,所以我决定使数组静态

2 个答案:

答案 0 :(得分:0)

private ArrayList<Point> points = new ArrayList<>();
private ArrayList<Point> temp;

private void addPoints(){
   this.points.add(new Point(num1,num2));
   //some more adds
}

private void newObject(){
    temp = new ArrayList<Point>();
    Iterator<Point> it = this.points.iterator();
    while(it.hasNext()) {
        temp.add(it.next());
    }
    Global.examples.add(temp);
    this.points.clear();
}

当你说Global.examples.add(new Example(this.points));实际上你正在复制对象this.points而不是它的内容时,发生了什么事情,在这种情况下,只有对象的副本被传递并存储在列表examples中当你清除this.points时,它的所有副本也会被清除,为了避免这种情况,你需要声明一个像temp这样的临时列表,并在每次要创建列表并将其添加到示例时使用新列表对其进行实例化

答案 1 :(得分:0)

您没有复制任何ArrayLists,因此只有一个newObject()。您需要修复private void newObject(){ Global.examples.add(new Example(new ArrayList<Point>(this.points))); this.points.clear(); }

https
相关问题