简体   繁体   English

使用for循环从ArrayList中删除特定对象

[英]Deleting specific object from ArrayList using for-loop

I am trying to delete one object from an ArrayList, but after iterating through the list with the for loop i'm stuck at what to do next. 我试图从ArrayList中删除一个对象,但是在使用for循环遍历列表之后,我陷入了下一步。 nameInput is a lowercase string from the user. nameInput是用户的小写字符串。

If i run this it prints the object from arr list equal to the input from nameInput. 如果我运行它,它将打印来自arr列表的对象,该对象等于来自nameInput的输入。 But I cannot understand how to go from printing that object to deleting it? 但是我不知道如何从打印该对象到删除它?

I'm sure this is a stupid question but the 50+ answers i have read and tried all seem to fail me (or more likely I fail to understand them). 我确定这是一个愚蠢的问题,但是我阅读并尝试过的50多个答案似乎都使​​我失望(或更可能是我听不懂)。 I have tried the list.remove and removeIf. 我已经尝试过list.remove和removeIf。

private ArrayList<Arr> arr = new ArrayList<>();

private void removeItem() {
    for (Object arr : arr) {
        if (((Arr) arr).getName().equals(nameInput())) {
            System.out.println(arr);        
            break;
        } else {
            System.out.println("Error");
        }
    }
}

Using for loop 使用for循环

List<Arr> arr = new ArrayList<>();

for (Arr item : arr) {
    if (item.getName().equals(nameInput())) {
        arr.remove(item);
        break;
    }
}

If not call break after remove element, you get ConcurrentElementException 如果在remove元素后未调用break ,则会出现ConcurrentElementException

Note from @Aomine : you have to implement correct Arr.equals() method. @Aomine的注释 :您必须实现正确的Arr.equals()方法。


Using Iterator 使用迭代器

List<Arr> arr = new ArrayList<>();
Iterator<Arr> it = arr.iterator();

while (it.hasNext()) {
    Arr items = it.next();

    if (item.getName().equals(nameInput())) {
        it.remove();
        break;  // you can continue iterating and remove another item
    }

}

Using Streams 使用流

List<Arr> arr = new ArrayList<>();
arr.removeIf(item -> item.getName().equals(nameInput()));

Remove all items that match given condition 删除所有符合给定条件的项目


This is not good to remove element from ArrayList . ArrayList删除元素不是很好。 In case you know that you have to remove element from the middle of the List , do use LinkedList . 如果您知道必须从List的中间删除元素,请使用LinkedList

You are trying to remove an item while you are traversing/iterating the list in the for loop. 在遍历/迭代for循环中的列表时,尝试删除项目。 You cannot remove an item from the list iterating it in a for loop. 您无法从列表中删除项目,并在for循环中对其进行迭代。 Use an Iterator instead and invoke arr.remove() . 改用Iterator并调用arr.remove()

If you use Java 8 you could do 如果您使用Java 8,则可以

private void removeItem() {
    arr.removeIf(t -> t.getName().equals(nameInput));
}

Note that this will remove all objects with name equal to nameInput 请注意,这将删除名称等于nameInput所有对象

Also you should change your declaration of arr to 您还应该将arr声明更改为

List<Arr> arr = new ArrayList<>();

A couple of things here... 这里有几件事...

  1. The loop variable receiver type should ideally be Arr instead of Object as the list contains Arr objects. 理想情况下,循环变量接收器类型应为Arr而不是Object因为列表包含Arr对象。 This also means you no longer need the cast you're performing. 这也意味着您不再需要执行的演员表。
  2. You could remove the item via remove(Object o) but this requires overriding equals and hashcode based on name only. 您可以通过remove(Object o)该项,但这需要重写equals和仅基于name hashcode Another option is via an iterator but this would mean changing your code completely. 另一个选择是通过迭代器,但这将意味着完全更改代码。 Thus, to keep it as close to your code as possible you can use a for loop; 因此,为了使其尽可能接近您的代码,可以使用for循环; get the index which the object is located and then remove. 获取对象所在的索引,然后将其删除。

Thus, you can do: 因此,您可以执行以下操作:

for(int i = 0; i < arr.size(); i++){
    if (arr.get(i).getName().equals(nameInput)) {
          Arr obj = arr.remove(i); // remove the item by index     
          System.out.println(obj);  // print the object             
          break;  // terminate the loop iteration
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM