2017-05-04 61 views
0

我正在實現此外觀以包裝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)` 

我已經按照幾乎是它的方式寫在其他問題,但它似乎我的循環仍然引發異常。

+0

爲什麼你完全合格的名稱是什麼? 'java.lang.String'不是必需的:只需使用'String'。你需要'import java.util.Collection;',但是你可以只寫'Collection'而不是'java.util.Collection'。 –

+0

這就是我們的大學員工想要他們的方式......他們還要求我們在3天前迭代一個沒有迭代器的集合:\ – tamir

回答

2

您的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); 
} 
+0

非常感謝! – tamir

相關問題