Joe Perkins
Joe Perkins

Reputation: 271

Copying array contents to a new array

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.

Upvotes: 0

Views: 79

Answers (5)

steffen
steffen

Reputation: 16938

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

theDirectory = Arrays.copyOf(theDirectory, theDirectory.length * 2);

Upvotes: 0

Orderoftheflame
Orderoftheflame

Reputation: 61

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

Upvotes: 1

Mena
Mena

Reputation: 48404

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]

Upvotes: 2

steffen
steffen

Reputation: 16938

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

Upvotes: 1

Scott Hunter
Scott Hunter

Reputation: 49803

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

Upvotes: 1

Related Questions