Java: How to make a copy of an array of an object?

Right now I have an array of Point objects and I want to make COPY of this array.

I tried the following methods:

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 these methods will be that for the temp, and not for the copy, only the mypointarray link is created.

For example, when I change the x coordinate of mypointarray [0] to 1 (the original value is 0), the x temp [0] coordinate also changes to 1 (I swear I did not touch the tempo).

So, are there any ways to make a copy of the Point array?

thanks

+8
java object arrays
source share
3 answers

You need to make a deep copy. There is no built-in utility for this, but it is quite simple. If Point has a copy constructor, you can do it like this:

 Point[] temp = new Point[mypointarray.length]; for (int i = temp.length - 1; i >= 0; --i) { Point p = mypointarray[i]; if (p != null) { temp[i] = new Point(p); } } 

This allows you to use the null elements of the array.

With Java 8, you can do this more compactly with threads:

 Point[] temp = Arrays.stream(mypointarray) .map(point -> point == null ? null : new Point(point)) .toArray(Point[]::new); 

And if you are guaranteed that no element of mypointarray is null , it can be even more compact, because you can eliminate the null test and use Point::new instead of writing your own lambda for map() :

 Point[] temp = Arrays.stream(mypointarray).map(Point::new).toArray(Point[]::new); 
+11
source share

you will have to create copies of all instances of Point yourself ...

while your point class is serializing, you can serialize + deserialize this array to get a quick deep copy

0
source share

You can use the Arrays utility class:

 import java.util.Arrays; ... Point[] copy = Arrays.<Point>copyOf(mypointarray, mypointarray.length); 
-2
source share

All Articles