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());
}
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With