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;
}
}
}
Checks if an array of primitive shorts is empty or null . Deprecated.
We can use an ArrayList to perform this operation. To remove an element from an array, we first convert the array to an ArrayList and then use the 'remove' method of ArrayList to remove the element at a particular index. Once removed, we convert the ArrayList back to the array.
In C programming, an array is derived data that stores primitive data type values like int, char, float, etc. To delete a specific element from an array, a user must define the position from which the array's element should be removed. The deletion of the element does not affect the size of an array.
The Java ArrayList removeAll() method removes all the elements from the arraylist that are also present in the specified collection. The syntax of the removeAll() method is: arraylist. removeAll(Collection c);
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 won't 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With