I need an array that I can determine its size from the start and if it has no more empty spaces then increase its size by X
. For example:
int arrayS
You cannot expand an array in Java. Once it is created, its size is fixed.
With ArrayList
this is not a problem at all, since it expands automatically to fit new elements as you .add()
them.
If you insist on using arrays anyway, you can use that:
intArray = Arrays.copyOf(intArray, newLength);
But use ArrayList
if you don't have a specific need for arrays. You can use .toArray()
on it to turn it into an array as well; note however that if this is an array of integers you'll have to use an Integer[]
-- there is unfortunately no method in the JDK which returns an int[]
from an Iterable
, and that is a pity. Guava has such a method, use Guava.
NOTE: don't use Vector
if you can help it; this class is completely obsolete in new code. Some parts of the JDK still use it for compatibility reasons, but that's about it. If you need concurrency, there is much better, for instance CopyOnWriteArrayList
.