简体   繁体   English

使用list.remove()时出现Java ConcurrentModificationException

[英]Java ConcurrentModificationException when using list.remove()

I've got a method called removeSup which is supposed to remove an object Supplement from a list of supplements. 我有一个称为removeSup的方法,该方法应该从补品列表中删除对象Supplement this is the code for the method: 这是该方法的代码:

private static void removeSup(Supplement supToRemove, List<Supplement> listToRemoveFrom) {
   Iterator<Supplement> iterator = listToRemoveFrom.iterator();
                while(iterator.hasNext()){
                    if(iterator.next().equals(supToRemove)){
                        iterator.remove();
                    }
                }
}

there is a class called magazine which defines the list of supplements. 有一个叫做magazine的类,它定义了补品清单。

public class Magazine {
  private List<Supplement> supList;
  public List<Supplement> getSupList() {
        return this.supList;
    }
  public void setSupList(List<Supplement> supList) {


      this.supList = supList;
        }
public Magazine(Double cost, String _name){
        this.supList = new ArrayList<>();
        this.weekCost = cost;
        this.name = _name;
    }
    }

the class supplement has the following constructor 该类supplement具有以下构造函数

public Supplement(String _name, Double _price, String _magName ){
        this.name=_name;
        this.price=_price;
        this.magName = _magName;
    }

in the main class client there is a search that the user can do to remove a certain Supplement 在主类client中,用户可以进行搜索以删除某些补充

private static void searchSup(){
   System.out.println("Search for Supplement");
        String search = scanner.nextLine();
        for (Supplement sup : magazine.getSupList()) {
            if (!sup.getSupName().equalsIgnoreCase(search)) {
         //do something
        }
        else{
              removeSup(sup,magazine.getSupList());
        }
    }

} the main method in the client class is as follows: 客户端类中的主要方法如下:

 private Magazine magazine;
        public static void main(String[] args) {
                magazine = new Magazine(3.0, "pop");
                List<Supplement> startList = new ArrayList<>();
            startList.add(new Supplement("Nat Geo", 3.0,"pop"));
            startList.add(new Supplement("Discovery", 5.0,"pop"));
            startList.add(new Supplement("Health", 6.3,"pop"));
            startList.add(new Supplement("IT", 8.3,"pop"));
            magazine.setSupList(startList);
            searchSup();
        }

When I run this program and type any of the added supplements, i get an error 当我运行该程序并键入任何添加的补充内容时,出现错误

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
    at java.util.ArrayList$Itr.next(ArrayList.java:831)
    at Client.searchSup(Client.java:131)
    at Client.searchSup(Client.java:140)
    at Client.main(Client.java:588)

is it the for loop i am using to search giving me an error? 我用来搜索的for循环给我一个错误吗? if so how would i go about fixing this? 如果是这样,我将如何解决这个问题?

You generally shouldn't modify a Collection while iterating over it. 通常,在迭代Collection时,通常不应该修改它。 It's fine to modify elements, but you really shouldn't remove something from a Collection while iterating. 修改元素很好,但是您实际上不应该在迭代时从Collection删除某些东西。 See here: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html . 参见此处: http : //docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html Also, the Javadoc for ConcurrentModificationException may be helpful. 另外, ConcurrentModificationException的Javadoc可能会有所帮助。

You might try returning a new list with the Supplement removed: 您可以尝试返回删除了Supplement的新列表:

 private static List<Supplement> removeSup(Supplement supToRemove, List<Supplement> listToRemoveFrom) {
    List<Supplement> filteredSupplements = new ArrayList<Supplement>();
    for(Supplement supplement : listToRemoveFrom) {
       if(!suppplement.equals(supToRemove)){
           filteredSupplements.add(supplement);
       }

    }

    return filteredSupplements;
}

它以“ main”方法接缝“ magazine”是局部变量,searchSup无法访问。像private void searchSup(Magazine magazine){// ...}和其他详细信息(如果可以提供的话)一样,将其固定在Line中131和140会有所帮助。

I figured out that the search i was doing was not working with what i wanted to do so i created a method which returns an integer of the Supplement in the list. 我发现我正在执行的搜索无法满足我的要求,因此我创建了一个方法,该方法返回列表中Supplement的整数。

private static int indexOfSup(List<Supplement> supSearchList, String nameOfSup) {
        for (Supplement sup : supSearchList) {
            if (sup.getSupName().equalsIgnoreCase(nameOfSup)) {
                return supSearchList.indexOf(sup);
            }
        }
        return -1;
    }

i then use this integer to remove from the list. 然后,我使用该整数从列表中删除。 a simple List.Remove(index) worked fine 一个简单的List.Remove(index)工作正常

Thanks for all the replies. 感谢所有的答复。

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

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