0

I am trying to write a method called reallocate, which takes an array called theDirectory, and copies it's contents over into a new array named newDirectory, which has twice the capacity. Then theDirectory is set to newDirectory.

This is what I have so far, however I am stuck on how to copy content across to newDirectory, so any help would be much appreciated.

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

   }

Thanks in advance.

Joe Perkins
  • 261
  • 3
  • 9
  • 17
  • http://stackoverflow.com/questions/8299771/copying-an-array-using-clone-original-array-being-changed?rq=1 – matcheek Mar 24 '14 at 16:13
  • Please accept an answer if it solved your problem or rephrase your question if you need further help. – steffen Oct 21 '18 at 21:27

5 Answers5

2

You can use System.arrayCopy for that.

API here.

Simple example with destination array with double capacity:

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));

Output

[4, 5, 6, 1, 2, 3]
Mena
  • 47,782
  • 11
  • 87
  • 106
1

Loop over the elements of the old array, and assign each to the corresponding position in the new array.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
1

Use System.arraycopy(theDirectory, 0, newDirectory, 0, theDirectory.length).

steffen
  • 16,138
  • 4
  • 42
  • 81
1

Have a look at System.arraycopy() :)

http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#arraycopy(java.lang.Object, int, java.lang.Object, int, int)

Should just be something like

System.arraycopy(oldArray, 0, newArray, 0, oldArray.size);
0

Check java.util.Arrays.copyOf(). This is what you want:

theDirectory = Arrays.copyOf(theDirectory, theDirectory.length * 2);
steffen
  • 16,138
  • 4
  • 42
  • 81