In Java, is there a way to add a value not at a specific index, but to the next undeclared index? Say:
int[] negativeArray = new int[21];
int[] positiveArray = new int[21];
There are two arrays for two different types of ints, for example negative and positive. I’m looping through this, and I want it to work something like a stack (I don’t know too much about stacks, but to my knowledge you don’t go through its index, you just pop/push items onto it) to where if its a negative number, put in the number in the next undeclared index spot in the negative array.
I thought of a way to do this with some extra code. I’d set all values in the array to 0. When checking if the variable is negative or positive, I would loop through the array to the next value that is 0. Once I find it I know what index I’m on. This would require a bit of effort though, are there any simpler ways of doing this?
Edit: Some comments are stating different ways to do this without using a basic array. I was assigned this, and I am required to use an array to get credit for it…
If you are actually using the array as a stack (and thus, will only add or remove items at the top of the stack) then you could keep in another variable the next free index in the array.
If removals can occur anywhere, then I don’t see a better solution than iterating over the array to find a free spot.