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.
int[] array = new int[21];
int nextIndex = 0;
public void push(int e) {
array[nextIndex] = e;
++nextIndex;
}
public int pop() {
--nextIndex;
return array[nextIndex];
}
If removals can occur anywhere, then I don't see a better solution than iterating over the array to find a free spot.
That is why List
have been made. Simply use something like this:
List<Integer> negativeIntegers = new ArrayList<Integer>(21);
...
negativeIntegers.add(-127);
If you want to create an array with the positive values and one with the negative values, you can do it with the algorithm you propose:
public static void main(String[] args) throws Exception {
int[] negativeArray = new int[3];
int[] positiveArray = new int[3];
int[] test = new int[] {1, -1, 2, -2, 3, -3};
int posIndex = 0;
int negIndex = 0;
for (int i = 0; i < test.length; i++) {
if (test[i] > 0) {
positiveArray[posIndex++] = test[i];
} else if (test[i] < 0) {
negativeArray[negIndex++] = test[i];
}
}
System.out.println(Arrays.toString(test)); //[1, -1, 2, -2, 3, -3]
System.out.println(Arrays.toString(positiveArray)); //[1, 2, 3]
System.out.println(Arrays.toString(negativeArray)); //[-1, -2, -3]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With