Copying Arrays: Copying Array References

Copying an array variable yields a second reference to the same array

Double[ ] values = new double[6];

// fill array . . .

Double[ ] prices = values;

Copying Arrays: making a true copy

To make a true copy of an array, call the Arrays.copyOf method:

  Double[ ] prices = Arrays.copyOf(values, values.length);

Copying Arrays: Copying Array Elements

To grow an array that has run out of space, use the Arrays.copyOf method

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

 

Example: Read an arbitrarily long sequence numbers into an array, without running out of space:

int valuesSize = 0;

while (in.hasNextDouble())

{

   if (valuesSize == values.length)

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

   values[valuesSize] = in.nextDouble();

   valuesSize++;  

}

 

How do you add or remove elements in the middle of an array list?

   Answer: Use the insert and remove methods.


Why do we double the length of the array when it has run out of space rather than increasing it by one element?

   Answer: Allocating a new array and copying the elements is   
   time-consuming. You wouldn't want to go through the process
   every time you add an element.