-2

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 ArrayLists.

I tried something as simple as swapping the operator values (from + to - and - to +) but that didn't work.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Ruairi
  • 3
  • 2
  • Copy the array youve got to one that is larger by one element. Then set the new element, which will be the highest-indexed element, to the added value. – Arfur Narf Apr 30 '23 at 13:21
  • Hi Arfur thanks for the reply! Would something below look ok? 'public void addObject(Object[] array, Object objectToAdd){ Object[] result = new Object[array.length + 1]; result[array.length - 1] = objectToAdd; }' – Ruairi Apr 30 '23 at 13:27
  • Java arrays have a fixed length. This isn't great when you want to add or remove objects from an array. And that is precisely why `ArrayList` is provided. Perhaps you should explain why you can't use `ArrayList` (I'm guessing it's because this is for school). You don't tell us very much, you ask for help with adding an element, but then show us code removing an element. Where exactly are you stuck? – Elliott Frisch Apr 30 '23 at 13:27
  • Hi Elliot thanks for the reply. Yes sorry it is for school hence the lack of Context. I created the code for removing an element and it is successfully working. I was wondering if the same code could just be slightly modified to be able to add rather than remove :) – Ruairi Apr 30 '23 at 13:29
  • Your new array (in the comment) does not contain what was in the old array. Use `Arrays.copy` for the whole old array, as in your remove code. Otherwise, you've got the idea. – Arfur Narf Apr 30 '23 at 13:52
  • Just keep an array of size 10 always and use as many entries as necessary. Keep track of how many using an `int` variable. When the user removes an element, push the elements to the right of the empty space one step to the left to fill the gap so that the unused entries are always at the end. So you know that if the count i 9, then the first 9 entries are used (from index 0 through 8), etc. – Ole V.V. Apr 30 '23 at 17:11

1 Answers1

1

The short answer in real code is to use an ArrayList. Since this is for learning, you need to understand a few things about Java arrays. They have a fixed length. And you need to know their type to create new ones. When you combine that with generics and subsequent type erasure, you are typically required to pass the type as an argument. Thus you end up with complex looking method signatures. Such as,

public static <T> T[] addObject(Class<? extends T> cls, T[] array, T obj) {
    int len = array != null ? array.length : 0; // The array length or 0 if null
    @SuppressWarnings("unchecked")
    T[] ret = (T[]) Array.newInstance(cls, len + 1); // at least one
    if (len > 0) { // check if there is something to copy
        System.arraycopy(array, 0, ret, 0, len); // copy the original array
    }
    ret[len] = obj; // append the new element
    return ret;
}

Where <T> defines some generic type, Class<? extends T> defines a class that produces instances of type T, and then an array of that type and an instance of T. Then, you can create a new instance of the array to return with java.lang.reflect.Array.newInstance(Class<?>, int), then copy the elements from the original array (if there are any) and finally append the new instance at the end before returning the new array. Testing it like,

public static void main(String[] args) {
    Integer[] arr = { Integer.valueOf(1), 2, 3 };
    Integer[] arr2 = addObject(Integer.class, arr, Integer.valueOf(4));
    System.out.println(Arrays.toString(arr2));
}

Outputs

[1, 2, 3, 4]
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • Hi Elliot, thanks for your patience with the lack of context and thank you for your answer. I will certainly give it a try and it has made me think of one or two ways I can implement into my code. Thank you :) – Ruairi Apr 30 '23 at 14:09
  • I will also read up on Arraycopy – Ruairi Apr 30 '23 at 14:09