gpt4 book ai didi

java - 门面实现中的 ConcurrentModificationException

转载 作者:行者123 更新时间:2023-12-02 02:51:25 24 4
gpt4 key购买 nike

我正在实现这个外观以在 java 中包装 LinkedList、TreeSet 和 HashSet 类。

import java.util.Iterator;

public class CollectionFacadeSet implements SimpleSet{
protected java.util.Collection<java.lang.String> collection;
private Iterator<java.lang.String> iterator;
private int count;
/**
* Creates a new facade wrapping the specified collection.
* @param collection - The Collection to wrap.
*/
public CollectionFacadeSet(java.util.Collection<java.lang.String> collection){

this.collection=collection;
iterator = this.collection.iterator();
count=0;
}
/**
* Add a specified element to the set if it's not already in it.
* @param newValue New value to add to the set
* @return False iff newValue already exists in the set
*/
public boolean add(java.lang.String newValue){
if(contains(newValue))
return false;
collection.add(newValue);
return true;
}
/**
* Look for a specified value in the set.
* @param searchVal Value to search for
* @return True iff searchVal is found in the set
*/
public boolean contains(java.lang.String searchVal){
while(iterator.hasNext())
{
java.lang.String myString=iterator.next(); //issue
System.out.println(myString);
if(myString.equals(searchVal))
return true;
}
return false;
}

在包含函数中,一旦我创建一个字符串来托管下一个(当前)对象,就会收到以下错误:

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.LinkedList$ListItr.checkForComodification(LinkedList.java:966)
at java.util.LinkedList$ListItr.next(LinkedList.java:888)`

我几乎按照其他问题中所写的方式进行操作,但看来我的循环仍然抛出异常。

最佳答案

创建迭代器后,您的 add 方法会修改集合。

不要将迭代器放在成员变量中,而是在 contains 方法中声明它:

public boolean contains(java.lang.String searchVal){
Iterator<String> iterator = collection.iterator();
while(iterator.hasNext()) {
// ...

当前代码的另一个问题是您的 contains 方法耗尽了迭代器 - 一旦您遍历一次并发现不包含该元素,它就不会重置,这意味着contains 方法下次将找不到该元素。将其声明为局部变量也可以解决此问题。

<小时/>

当然,除了打印元素之外,您根本不需要迭代器。 (我猜你这样做只是为了调试;它并不是真正有用)。

您可以简单地使用Collection.contains:

public boolean contains(String searchVal) {
return collection.contains(searchVal);
}

关于java - 门面实现中的 ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43791587/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com