java – How to use ArrayUtils for array of objects, it doesnt delete the content of an array

java – How to use ArrayUtils for array of objects, it doesnt delete the content of an array

Change this

ArrayUtils.remove(listItems, i);

to

listItems = ArrayUtils.remove(listItems, i);

As you can see in the JavaDoc, the method does not change the argument listItems, rather it returns a new array with the remaining elements.

Edit

You also need to change your deletion method to

public static ItemTracker[] deleteItem(ItemTracker[] listItems) {
    //..
}

So you could return the new array with the remaining elements.

Store the resulting array.

It wont change the original array object.

listItems = ArrayUtils.remove(listItems, i);

Edit: But for using this method you need the change to return type of your method

public static ItemTracker[] deleteItem(ItemTracker[] listItems){
    System.out.println(Which item you want to delete? );
    for(int i=0; i < listItems.length; i++) {
            if(input.equalsIgnoreCase(Quantity)) {
                // Some Code
            } else if(input.equalsIgnoreCase(Something){
                listItems = ArrayUtils.remove(listItems, i); //  This is the part where it should delete .. but it doesnt delete. 
            } 
            break;
        }
      return listItems;
      }

java – How to use ArrayUtils for array of objects, it doesnt delete the content of an array

In your case usage of ArrayUtils is incorrect and redundant. You can delete element in next way:

// ...  
listItems[i] = null;
// array will looks like [o1, o2, null, o3, o4, ...]
// ...    

There is no other way without changing methods return type

Leave a Reply

Your email address will not be published.