I wonder if it's possible to extend an array in Java but without changing its name, since I have multiple methods linked to this array. I was thinking of creating a new array with the same name but twice as big, and then copy all elements from the first array to the second. Is this possible?
Basically I want to make an array with accounts at a bank, and if the customer creates so many accounds that the array doesn't have enough elements, it should extend itself.
Thank you for any replies!
Even if using an ArrayList
is probably a good advice in many circumstances, there are perfectly legitimate occasions for using plain old arrays.
In that case, if you need to resize your array, you might want to investigate one of the java.utils.Arrays.copyOf
methods. Please note however those won't really resize your array. They will merely create a new array and copy common items.
If the new array has a size greater than the old one, the new items will be initialized to some default value (i.e.: false
for boolean[]
, null
for T[]
-- see the documentation for details). You have to use those function like that:
myArray = copyOf(myArray, myNewSize);
Remember however that this method will always return a new array. Even if the requested size is the same as the original one. If this in not desirable, you will have to write something like that:
myArray = (myNewSize > myArray.length) ? copyOf(myArray, myNewSize) : myArray;