java10:複製數組

對於基本數據類型,例如 char a , 我們可以直接用char b=a  進行基本數據類型變量的複製,但是由上一篇我們知道,數組名其實是指向數據元素的一個引用,如如直接用 array list2=list1 是不能達到數組的複製的,他只是將list2也指向了list1指向的內存空間。也成了數組的引用。

In Java, you can use assignment statements to copy primitive data type variables, but not
arrays. Assigning one array variable to another array variable actually copies one reference to
another and makes both variables point to the same memory location.
There are three ways to copy arrays:
■ Use a loop to copy individual elements one by one.
■ Use the static arraycopy method in the System class.
■ Use the  clone method to copy arrays; this will be introduced in Chapter 14,
“Abstract Classes and Interfaces.”

有三種方法實現數組的複製

1) 自己寫個循環一個一個元素的複製

2)使用system類的類方法 arraycopy

3)使用clone方法,在後面講到抽象類時候講到

方法1使用一個循環例如:

int [] source ={12,45,67,7};

int [] targer=new int[source.lenght];

for(int=0;i<target.length;i++)

target[i]=source[i];

在方法2)中,System.arraycopy(sourceAarry,src_pos, targetArray,tar_pos,length); 參數從左到右分別是 源數組,源數組起始位置,目標數組,目標數組起始位置,複製的長度;但是在使用該方法時候一定要注意,targetarray必須是事先申請好內存的。

The arraycopy method does not allocate memory space for the target array. The target array
must have already been created with its memory space allocated. After the copying takes
place, targetArray and sourceArray have the same content but independent memory
locations.

例子:

public class CopyArray
{
	public static void main(String [] args)
	{
		int [] source={2,3,8,56};
		int [] target=new int[source.length];
		for(int i=0;i<target.length;i++)
		{
			target[i]=source[i];
		}
		for(int i=0;i<target.length;i++)
			System.out.println(target[i]);
		int [] tarCopy=new int[source.length];
		System.arraycopy(source,0,tarCopy,0,source.length);
		for(int i=0;i<tarCopy.length;i++)
			System.out.print(tarCopy[i]+"    ");
		
	}
}

運行如下:


如果我們將上面的int [] tarCopy=new int[source,length]換爲 int [] tarCopy;則會出現未初始化的提示:




發佈了112 篇原創文章 · 獲贊 15 · 訪問量 22萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章