Java array, add item to next empty index

In Java, is there a way to add a value not to 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 int types, for example, negative and positive. I focus on this and I want it to work like a stack (I don’t know too much about stacks, but as far as I know, you don’t look at its index, just click objects on it) where, if it's a negative number, enter the number in the next undeclared index spot in the negative array.

I was thinking of a way to do this with extra code. I would set all the values ​​in the array to 0. When I check if the variable is negative or positive, I would iterate over the array to the next value equal to 0. As soon as I find it, I know in which index I am included. It will take a little effort, but are there any simpler ways to do this?


Edit: some comments indicate different ways to do this without using a base array. I was assigned this, and I have to use an array to get a loan for it ...

+4
source share
4 answers

If you are actually using the array as a stack (and thus will only add or remove elements at the top of the stack), you can store the next free index in the array in another variable.

 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 deletion can happen anywhere, then I see no better solution than repeating the array to find free space.

+5
source

That is why List was made. Just use something like this:

 List<Integer> negativeIntegers = new ArrayList<Integer>(21); ... negativeIntegers.add(-127); 
+2
source

Check out http://docs.oracle.com/javase/6/docs/api/java/util/Stack.html

This is basically the same as the ARRG solution, but with fewer lines of code:

 Stack<Integer> negative = new Stack<Integer>(); Stack<Integer> positive = new Stack<Integer>(); public void putMyNumber(int number) { // Taking 0 as "positive" if (number >= 0) { positive.push(number); //Auto-boxing return; } negative.push(number); } 
0
source

If you want to create an array with positive values ​​and one with negative values, you can do this using 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] } 
0
source

Source: https://habr.com/ru/post/1396656/


All Articles