Java数组的深拷贝与浅拷贝

时间:2021-12-19 19:49:31

  1.Java数组深拷贝,也就是引用传递,影响原来的值,可以直接进行赋值:

int arraySource[] = {1,2,3};

int length = arraySource.length;

int arrayDest[] = new int[length];

arrayDest = arraySource;

  对arrayDest的操作影响arraySource的值。

  2.Java数组浅拷贝,值传递,不影响原来的值:

system.arrayCopy(Object src,int srcPos,Object dest,int destPos,int length);

system.arrayCopy(arraySource,0,arrayDest,0,length);

  对arrayDest的操作不影响arraySource的值。

另有一种clone方法,未曾研究。


栗子

public class FartherJava {	
        public FartherJava() {
		buf =new short[3];
		for(short i = 0;i<3;i++)
		{
			buf[i] = i;
		}
        private short[] buf;
	
	public short[] retArray()
	{

		return buf;
	}
	
	public int getArrayLength()
	{
		return buf.length;
	}
	
	public void printArray()
	{
		System.out.println();
		System.out.println("original array:");
		for (short i : buf) {
			System.out.print(i);			
		}
	}
	
	public static void main(String args[]) {
		FartherJava m = new FartherJava();		
		short[] getArray = new short[10];
		getArray = m.retArray();
		int len = m.getArrayLength();		
		getArray[0] = 4;
		System.out.println("getArray:");
		for(short s : getArray) {
			System.out.print(s);
		}	
		m.printArray();
		System.out.println();
		
		short[] getAy = new short[len];
		System.arraycopy(m.retArray(), 0, getAy, 0, 3);
		getAy[0] = 3;
		System.out.println("getAy:");
		for (short s : getAy) {
			System.out.print(s);
		}
		m.printArray();
	}
}

输出:

getArray:
412
original array:
412
getAy:
312
original array:
412