Suppose you have a method that outputs arrays of different sizes.
Before you use it, you need to create an array reference variable. Before you can do that, you need to find the array length, e.g.
int[] intArray = new int[methodReturnsArray().length]
And then you can set intArray to your array produced by methodReturnsArray().
I feel a bit uneasy about this, because we’re calling methodReturnsArray() twice: once to find out how big the array is, and again to set it equal to the reference variable.
Is that wasting resources to call the method twice, or is the array only created once (when you find its size)?
Edit: I know you can just initialize intArray to the method returned by the array. But for some complicated reasons (to do with “methodReturnsArray” being called in a loop with a different-sized array for each iteration) I need to know whether calling twice will waste computational resources.
It depends on how you will then fill new array variable.
But the common approach will be introducing new local variable for saving reference to original array from method
methodReturnsArray. i.e.:Then the best way for copying an array is
System.arrayCopy(...)method.This approach will work in any case, and it will prevent you from doing things in method
methodReturnsArraytwice.