Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList, java. Whats the difference between these two constructors

Tags:

java

I'm kind of a newbie still in java, can you tell me whats the difference between these two constructors?

First:

public class Plan
{

   ArrayList<Point2D> points;

   public Plan(ArrayList<Ponto2D> points)
   {
       this.points = new Arraylist<Point2D>(points);
   }

}

and this : second:

public class Plan
{

    public Plan(ArrayList<Point2D> lpoints)
    {
        points = new ArrayList<Point2D>();
        for(Point2D p : lpoints) point.add(p.clone());
    }

}
like image 270
Richard Avatar asked Aug 26 '15 14:08

Richard


2 Answers

The first constructor is a shallow copy, the second one a deep copy.

Answer given by S.Lott for this question.

Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements.

Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated.

like image 175
NiziL Avatar answered Nov 14 '22 22:11

NiziL


this.points = new Arraylist<Point2D>(points);

This takes a whole collection and uses the collection to initlaize your points ArrayList.

for(Point2D p : lpoints) point.add(p.clone());

That has the same result but adds each element of the lpoints-collection one by one to your points list.

So for your usage, use the first possibility.

like image 42
Christian Avatar answered Nov 14 '22 21:11

Christian