【问题标题】:ConcurrentModificationException in facade implemention外观实现中的 ConcurrentModificationException
【发布时间】:2017-05-04 19:44:57
【问题描述】:

我正在实现这个外观以在 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)`

我几乎遵循了它在其他问题中所写的方式,但似乎我的循环仍然抛出异常。

【问题讨论】:

  • 您为什么要完全限定名称? java.lang.String 不是必需的:只需使用 String。你需要import java.util.Collection;,但是你可以写Collection而不是java.util.Collection
  • 这就是我们大学工作人员想要他们的方式......他们还要求我们在没有迭代器的情况下迭代一个集合,直到 3 天前:\

标签: java facade


【解决方案1】:

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

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

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

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


当然,您根本不需要Iterator,除了打印出元素这一事实。 (我猜你这样做只是为了调试;它并不是很有用)。

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

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

【讨论】:

  • 非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-10
  • 1970-01-01
  • 1970-01-01
  • 2012-10-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多