Reputation:
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.
Upvotes: 2
Views: 34200
Reputation: 838876
Arrays don't have "free space". You can use a "magic value" (e.g. zero, or null depending on the type) to represent empty if you wish. Then you can search through the array looking for this value:
int i = Array.asList(array).indexOf(0.0);
A few warnings:
If you just want a collection that can contain a variable number of elements then don't use an array. For example, you could use an ArrayList
and its add
method to add elements to the end.
Upvotes: 4
Reputation: 81724
This makes far more sense for an array of object references, where null
clearly means "empty". But let's just assume that for an array of double
, maybe 0
means "empty". So...
int index = -1;
for (int i=0; i<array.length; ++i) {
if (array[i] == 0) {
array[i] = 5;
index = i;
break;
}
}
Then index
points to the element you set, or is -1
if the array was full.
Upvotes: 1
Reputation: 425238
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:
double[] myArray = new double[10];
int nextIndex = 0;
myArray[nextIndex++] = 1234;
... etc
myArray[nextIndex++] = 1.0;
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 automatically
and is easy to add to.
Upvotes: 7