2014-03-24 51 views
0

我正在尝试编写一个名为reallocate的方法,它需要一个名为theDirectory的数组,并将其内容复制到一个名为newDirectory的新数组中,该数组的容量是其两倍。然后将目录设置为newDirectory。将数组内容复制到一个新的数组

这是我迄今为止,但我坚持如何将内容复制到newDirectory,所以任何帮助将不胜感激。

private void reallocate() 
    { 
     capacity = capacity * 2; 
     DirectoryEntry[] newDirectory = new DirectoryEntry[capacity]; 
     //copy contents of theDirectory to newDirectory 
     theDirectory = newDirectory; 

    } 

在此先感谢。

+0

http://stackoverflow.com/questions/8299771/copying-an-array-using-clone-original-array-being-changed?rq=1 – matcheek

回答

1

循环遍历旧数组的元素,并将其分配给新数组中的相应位置。

2

您可以使用System.arrayCopy

API here

与双倍容量目标阵列的简单例子:

int[] first = {1,2,3}; 
int[] second = {4,5,6,0,0,0}; 
System.arraycopy(first, 0, second, first.length, first.length); 
System.out.println(Arrays.toString(second)); 

输出

[4, 5, 6, 1, 2, 3] 
相关问题