I’m trying to find a way to add an element to an array without knowing where to add it. E.g. Instead of doing something like this…
double[] myArray = new double[10];
myArray[5] = 1.0;
I want to be able to just add an element to the next available free space. Is this even possible in java? Sorry if it’s a simple question, I’m pretty new to the language.
Firstly, define “free”. You can’t look for the first zero value; what if you actually wanted to store zero as a real value.
The only way is to keep track of where you last inserted:
Note that this is deliberately simplistic. It does not protect against running off the end of the array etc.
Your better option is to use a Collection, like
ArrayList, which expands automaticallyand is easy to add to.