Naufal Yahaya Naufal Yahaya - 1 month ago 21
Java Question

How to use ArrayUtils for array of objects, it doesnt deleted the content of an array

How to delete the content of an array of objects. If there is other ways to delete a content of an array of objects , please do share.

import java.util.Arrays;
import java.util.Scanner;

import org.apache.commons.lang3.ArrayUtils;


public class Testing {


public static void 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"){
ArrayUtils.remove(listItems, i); // This is the part where it should delete .. but it doesnt delete.
}
break;
}
}

}

Tom Tom
Answer

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.