방금 두 번째 boolean
어레이에 .clone()
어레이를 사용하여 비트를 얻었습니다.이 어레이는 완전한 복사본이라고 생각했습니다.Java에서 2 차원 배열의 전체 복사본을 만드는 방법은 무엇입니까?
boolean[][]
배열의 전체 복사본을 어떻게 수행합니까?
System.arraycopy
의 일련 번호를 반복해야하나요?
방금 두 번째 boolean
어레이에 .clone()
어레이를 사용하여 비트를 얻었습니다.이 어레이는 완전한 복사본이라고 생각했습니다.Java에서 2 차원 배열의 전체 복사본을 만드는 방법은 무엇입니까?
boolean[][]
배열의 전체 복사본을 어떻게 수행합니까?
System.arraycopy
의 일련 번호를 반복해야하나요?
예, 2D 부울 배열을 반복하여 딥 복사해야합니다.
public static boolean[][] deepCopy(boolean[][] original) {
if (original == null) {
return null;
}
final boolean[][] result = new boolean[original.length][];
for (int i = 0; i < original.length; i++) {
result[i] = Arrays.copyOf(original[i], original[i].length);
// For Java versions prior to Java 6 use the next:
// System.arraycopy(original[i], 0, result[i], 0, original[i].length);
}
return result;
}
는 예, 그것을 할 수있는 유일한 방법이다 : 당신은 자바 6에
내가 자바 6에 대한 다음 코드를 제안하는 경우도 java.util.Arrays#copyOf
방법을 살펴 봅니다. java.util.Arrays
은 커먼 스 - 랭 (commons-lang)이 아니라 어레이에 대한 딥 (deep) 복사본을 제공하지 않습니다.
난 Arrays 유틸리티의 팬이야. 그것은 당신을 위해 1-D 배열의 깊은 사본을 할 것 copyOf 방법이있다, 그래서 당신은 이런 식으로 뭔가 싶어 : 나는 관리했습니다
//say you have boolean[][] foo;
boolean[][] nv = new boolean[foo.length][foo[0].length];
for (int i = 0; i < nv.length; i++)
nv[i] = Arrays.copyOf(foo[i], foo[i].length);
참고, 원시 타입에 대해서만 "딥 카피"를 생성합니다! Arrays.copyOf() 자체는 얕은 복사본 만 만듭니다. – codepleb
재귀 배열 전체 복사본을 마련 할 수 있습니다. 다양한 치수 길이를 갖는 다차원 배열에도 꽤 잘 작동하는 것처럼 보입니다.
private static final int[][][] INT_3D_ARRAY = {
{
{1}
},
{
{2, 3},
{4, 5}
},
{
{6, 7, 8},
{9, 10, 11},
{12, 13, 14}
}
};
다음은 유틸리티 메소드입니다.
@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);
}
편집 : 원시적 배열 함께 작동하도록 코드를 업데이트했습니다.
자바 (8) 이것은 한 라이너를 사용하여 람다으로 수행 할 수 있습니다 :이 Objects``작동하지 않는 것
<T> T[][] deepCopy(T[][] matrix) {
return java.util.Arrays.stream(matrix).map(el -> el.clone()).toArray($ -> matrix.clone());
}
하는 것으로. http://stackoverflow.com/questions/15135104/system-arraycopy-copies-object-or-reference-to-object – Timo