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:
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.
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:
- This will be slow as it requires scanning the array.
- You must be certain that the magic value can't occur as an element that you wish to store in the array.
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.
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.
精彩评论