Right now, I have an array of Point objects and I want to make a COPY of that array.
I have tried following ways:
1) Point[] temp = mypointarray;
2) Point[] temp = (Point[]) mypointarray.clone();
3)
Point[] temp = new Point[mypointarray.length];
System.arraycopy(mypointarray, 0, temp, 0, mypointarray.length);
But all of those ways turn out to be that only a reference of mypointarray is created for temp, not a copy.
For example, when I changed the x coordinate of mypointarray[0] to 1 (the original value is 0), the x coordinate of temp[0] is changed to 1 too (I swear I didn’t touch temp).
So is there any ways to make an copy of Point array?
Thanks
You need to make a deep copy. There’s no built-in utility for this, but it’s easy enough. If
Pointhas a copy constructor, you can do it like this:This allows for null array elements.
With Java 8, you can do this more compactly with streams:
And if you’re guaranteed that no element of
mypointarrayisnull, it can be even more compact because you can eliminate thenulltest and usePoint::newinstead of writing your own lambda formap():