How to Remove Objects from an Array in Java

deleting an object from an array [java]

you can replace the employee with null whenever want to delete it. when inserting a new emplyee, you can first look at a null index and place it.

private void deleteEmployee(){

Scanner scan = new Scanner(System.in);
System.out.println("Enter the first name of the employee you want to delete from the list")
String name = scan.nextLine();

for (int i = 0; i < employees.length; i++) {
if (employee[i] != null && employees[i].getFirstName().equals(name)){
employees[i] = null;
break;
}

if (i == employees.length - 1) {
System.out.println("That requested person is not employed at this firm.")
}
}

How do I remove objects from an array in Java?

[If you want some ready-to-use code, please scroll to my "Edit3" (after the cut). The rest is here for posterity.]

To flesh out Dustman's idea:

List<String> list = new ArrayList<String>(Arrays.asList(array));
list.removeAll(Arrays.asList("a"));
array = list.toArray(array);

Edit: I'm now using Arrays.asList instead of Collections.singleton: singleton is limited to one entry, whereas the asList approach allows you to add other strings to filter out later: Arrays.asList("a", "b", "c").

Edit2: The above approach retains the same array (so the array is still the same length); the element after the last is set to null. If you want a new array sized exactly as required, use this instead:

array = list.toArray(new String[0]);

Edit3: If you use this code on a frequent basis in the same class, you may wish to consider adding this to your class:

private static final String[] EMPTY_STRING_ARRAY = new String[0];

Then the function becomes:

List<String> list = new ArrayList<>();
Collections.addAll(list, array);
list.removeAll(Arrays.asList("a"));
array = list.toArray(EMPTY_STRING_ARRAY);

This will then stop littering your heap with useless empty string arrays that would otherwise be newed each time your function is called.

cynicalman's suggestion (see comments) will also help with the heap littering, and for fairness I should mention it:

array = list.toArray(new String[list.size()]);

I prefer my approach, because it may be easier to get the explicit size wrong (e.g., calling size() on the wrong list).

Java - Removing an object from an object array

Create unit tests for your classes especially if you going to build 'big and complicated program'. This will guarantee you that the code written will work later and if you change your code the failure of unit tests should indicate a problem. The unit test also gives you ability to check that your method works as expected.

As per other comments, consider using List interface instead of array, unless you have some specific requirement (I cannot imagine any). And definitely, having public static fields in your class looks suspicious.

EDIT

Just to indicate how code can look like and how to call methods from the main method.

public class Player {

private String name;
private List<Item> inventory;
private int items;

public Player() {
this.inventory = new ArrayList();
}

public void addItem(String itemName, int itemType) {
this.inventory.add(new Item(itemName, itemType));
}

public void removeItem(int x) {
Item itemToRemove = this.inventory.get(x);
if (itemToRemove != null) {
this.inventory.remove(itemToRemove);
}
}

public static void main(String[] args) {
// create a new instance
Player player = new Player();
// call a method on the instance
player.addItem("bla", 0);
}
}

Java: How to remove objects from an Array depending on the condition?

I think the best Java way to tackle your problem is to convert your array into a list and use an iterator which allows you to remove objects:

List<File> files = new ArrayList<File>(Arrays.asList(file.listFiles()));
Iterator<File> iterator = files.iterator();
while(iterator.hasNext()){
File currentFile = iterator.next();
if(someCondition){
iterator.remove();
}
// other operations
}

You can even convert it again into an array if necessary -even though handling a list is probably more convenient ...:

File[] filesArray = files.toArray();


Related Topics



Leave a reply



Submit