【发布时间】: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 天前:\