需要类似C memcpy函数的Java数组复制方法,网上一查,Java只有System.arraycopy,clone等方法,对二维数组都只能复制其一维数组的引用,改这个那个也变了,蛋疼,转为一维数组又貌似有点麻烦。而类似memcpy的功能没有具体的实现,只好试着写一个,貌似效率较低。。。
结果:
代码:
package _normaltest;
public class test {
public test() {
}
public static void main(String[] args) {
int a[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 0, 9, 9 } };
int b[][] = new int[3][4];
int c[] = new int[12];
System.out.print("各数组大小:a[" + a.length + "][" + a[0].length + "]");
System.out.print(" b[" + b.length + "][" + b[0].length + "]");
System.out.println(" c[" + c.length + "]\n");
// b = a.clone();
// System.arraycopy(a, 0, b, 0, a.length);// 通过arraycopy()函数拷贝数组
int srcStart = 2;
int desStart = 4;
int length = 5;
for (int i = 0; i < length; ++i) {
b[(desStart - 1 + i) / b[0].length][(desStart - 1 + i) % b[0].length] = a[(srcStart - 1 + i) / a[0].length][(srcStart - 1 + i)
% a[0].length];
}
for (int i = 0; i < length; ++i) {
c[desStart - 1 + i] = a[(srcStart - 1 + i) / a[0].length][(srcStart - 1 + i) % a[0].length];
}
a[0][0] = 0; // 改变a的值
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
System.out.print("a[" + i + "][" + j + "]:" + a[i][j] + " ");
}
System.out.println();
}
System.out.println();
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b[0].length; j++) {
System.out.print("b[" + i + "][" + j + "]:" + b[i][j] + " ");
}
System.out.println();
}
System.out.println();
for (int i = 0; i < c.length; i++) {
System.out.print("c[" + i + "]:" + c[i] + " ");
}
}
}