Java:如何制作一个对象数组的副本?

kev*_*vin 11 java arrays object

现在,我有一个Point对象数组,我想对该数组进行复制.

我试过以下方法:

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);
Run Code Online (Sandbox Code Playgroud)

但所有这些方式都证明只有mypointarray的引用是为temp创建的,而不是副本.

例如,当我将mypointarray [0]的x坐标更改为1(原始值为0)时,temp [0]的x坐标也会更改为1(我发誓我没有触摸temp).

那么有没有办法制作Point数组的副本?

谢谢

Ted*_*opp 17

你需要做一个深层复制.没有内置的实用程序,但它很容易.如果Point有一个复制构造函数,你可以这样做:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这允许空数组元素.

使用Java 8,您可以使用流更紧凑地执行此操作:

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

如果你保证,没有的元素mypointarraynull,它可以更加紧凑,因为可以消除null测试和使用Point::new,而不是写自己的λ为map():

Point[] temp = Arrays.stream(mypointarray).map(Point::new).toArray(Point[]::new);
Run Code Online (Sandbox Code Playgroud)