ArrayList, java. What is the difference between these two constructors

I'm kind of a newbie, still in java, can you tell me what is 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()); } } 
+5
source share
4 answers

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

Answer received by S. Lott for this question .

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

Deep copies duplicate everything. Deep copy of the collection - two collections with all the elements in the original collection are duplicated.

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

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

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

This has the same result, but each lpoints -collection element adds one to one to your points list.

So, for your use, use the first opportunity.

+3
source

in the first case, the ArrayList parameter separates the same points (p1.equals (p2) will be true, p1 == p2 will be true) in the second case they have a different copy of points (p1.equals (p2) will be true, but p1 == p2 will be false)

+1
source

In your first constructor, you use the default Java Constructor to create an ArrayList that takes a collection as an argument.

( From Java docs )

public ArrayList (Collection <? extends E> c)

Creates a list containing the elements of the specified collection in the order in which they are returned by the collection iterator.

This is basically the same as writing your own iterator (from your example).

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

In this example, however, we use a method called .clone () because we do not want each object to represent a shallow copy. We want to duplicate them.

[Edit]: Both examples do not do the same. The first is a shallow copy, and the second is a deep copy.

+1
source

All Articles