tôi đã quản lý để đưa ra một bản sao sâu mảng đệ quy. Dường như nó hoạt động khá tốt ngay cả đối với mảng đa chiều với độ dài thứ nguyên khác nhau, ví dụ:
private static final int[][][] INT_3D_ARRAY = {
{
{1}
},
{
{2, 3},
{4, 5}
},
{
{6, 7, 8},
{9, 10, 11},
{12, 13, 14}
}
};
Đây là phương pháp tiện ích.
@SuppressWarnings("unchecked")
public static <T> T[] deepCopyOf(T[] array) {
if (0 >= array.length) return array;
return (T[]) deepCopyOf(
array,
Array.newInstance(array[0].getClass(), array.length),
0);
}
private static Object deepCopyOf(Object array, Object copiedArray, int index) {
if (index >= Array.getLength(array)) return copiedArray;
Object element = Array.get(array, index);
if (element.getClass().isArray()) {
Array.set(copiedArray, index, deepCopyOf(
element,
Array.newInstance(
element.getClass().getComponentType(),
Array.getLength(element)),
0));
} else {
Array.set(copiedArray, index, element);
}
return deepCopyOf(array, copiedArray, ++index);
}
EDIT: Cập nhật mã để làm việc với mảng nguyên thủy.
Nguồn
2013-04-27 19:39:15
Lưu ý rằng điều này dường như không làm việc cho 'Objects'. Xem http://stackoverflow.com/questions/15135104/system-arraycopy-copies-object-or-reference-to-object – Timo