我正在實現此外觀以包裝Java中的LinkedList,TreeSet和HashSet類。在Facade實現中的ConcurrentModificationException
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天前迭代一個沒有迭代器的集合:\ – tamir