问题描述
现在,我有一个Point对象数组,我想制作该数组的 COPY 。
Right now, I have an array of Point objects and I want to make a COPY of that array.
我试过以下方式:
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);
但所有这些方式都证明只有mypointarray的引用是为temp创建的,而不是一个副本。
But all of those ways turn out to be that only a reference of mypointarray is created for temp, not a copy.
例如,当我将mypointarray [0]的x坐标更改为1(原始值为0)时,temp [0]的x坐标也改为1(我发誓我没有触摸临时)。
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).
那么有没有办法制作Point数组的副本?
So is there any ways to make an copy of Point array?
谢谢
推荐答案
您需要制作一份深层副本。没有内置的实用程序,但它很容易。如果 Point
有一个复制构造函数,你可以这样做:
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);
}
}
这允许空数组元素。
使用Java 8,您可以使用流更紧凑地执行此操作:
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);
如果你保证没有元素 mypointarray
是 null
,它可以更紧凑,因为你可以消除 null
测试并使用 Point :: new
而不是为编写自己的lambda map()
:
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);
这篇关于Java:如何制作一个对象数组的副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!