13

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

kevin
  • 807
  • 3
  • 11
  • 20
  • 1
    what you doing i believe is shallow copy.you have option to use copy constructor.follow this thread http://stackoverflow.com/questions/3947227/deep-copy-of-an-object-array – Umesh Awasthi Nov 20 '11 at 06:48
  • 2
    http://stackoverflow.com/questions/2156120/java-recommended-solution-for-deep-cloning-copying-an-instance/2156367#2156367 – Bozho Nov 20 '11 at 07:17

3 Answers3

21

You need to make a deep copy. There's no built-in utility for this, but it's easy enough. 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 for null array elements.

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

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

And if you're 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);
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • What if the class doesn't has a copy constructor? – aniztar May 18 '19 at 13:44
  • @aniztar -- Well, presumably the class provides *some* mechanism for making a copy of an instance (another constructor; a `copy()` method; a builder class; serialize/deserialize; `clone()`; something) so just use whatever's available where I was using a copy constructor. If you have no way of making a copy of an instance, then you're pretty much out of luck. – Ted Hopp May 19 '19 at 04:03
0

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

as long as your Point Class is serializable, you can serialize + deserialize that array to obtain a quick deep copy

DarkSquirrel42
  • 10,167
  • 3
  • 20
  • 31
-3

You can use the Arrays utility class:

import java.util.Arrays;
...
Point[] copy = Arrays.<Point>copyOf(mypointarray, mypointarray.length);
Finbarr
  • 31,350
  • 13
  • 63
  • 94