I was wondering if someone could help me with how to add an object to an array. For some context my program prints out 10 objects from an array and allows the user to select one to be removed, then shows the remaining nine and allows them to select another one to be removed (Using switch case statements). The program then compares the objects and if they equal a certain value then they are permanently removed, if not they are added back. I have the method below that I use to remove the object but I was hoping I could get some help with modifying the method but to ADD an object rather than REMOVE it.
public void removeObjectFromArray(int index) {
this.array = removeElement(array, index);
}
public static Object[] removeElement(final Object[] array, final int index) {
Object[] result = new Object[array.length - 1];
System.arraycopy(array, 0, result, 0, index);
if (index < array.length - 1) {
System.arraycopy(array, index + 1, result, index, array.length - index - 1);
}
return result;
}
Any alternatives are also appreciated. But I am supposed to avoid using ArrayList
s.
I tried something as simple as swapping the operator values (from + to - and - to +) but that didn't work.