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.
Answer from ARRG on Stack OverflowWithout using an ArrayList how would you insert a value into the middle of an array? Java
Java array, add item into next empty index - Stack Overflow
java - How to add item to array without using built-in methods - Stack Overflow
java - How to add an element to Array and shift indexes? - Stack Overflow
So for my homework I have to do a lot of array editing and already have a some code for the original array and for adding one element to the end. Iโm not sure where I should fit this into the code. I know I need the length of the updated array but am not sure which method to use. Browsing the Java API I saw a couple possibilities like copyOf() or addPos()โฆI could add the code but am curious to hear your approach to this and appreciate your help.
Thank you
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 Listhave been made. Simply use something like this:
List<Integer> negativeIntegers = new ArrayList<Integer>(21);
...
negativeIntegers.add(-127);
The most simple way of doing this is to use an ArrayList<Integer> and use the add(int, T) method.
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);
// Now, we will insert the number
list.add(4, 87);
This should do the trick:
public static int[] addPos(int[] a, int pos, int num) {
int[] result = new int[a.length];
for(int i = 0; i < pos; i++)
result[i] = a[i];
result[pos] = num;
for(int i = pos + 1; i < a.length; i++)
result[i] = a[i - 1];
return result;
}
Where a is the original array, pos is the position of insertion, and num is the number to be inserted.
I cannot find a solid answer for the love of me. I don't need to resize the array, I just want to add elements to an array so the most recently added element goes in the furthest spot. Array of a class object btw. Why does Java not have an append API like C does? Thanks.