2017-05-04 3 views
0

私はこのファサードを実装して、LinkedList、TreeSetおよびHashSetクラスをjavaでラップします。含まれている機能でファサードの実装における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'を使います。 'java.util.Collection;をインポートする必要がありますが、' java.util.Collection'の代わりに 'Collection'だけ書くことができます。 –

+0

これは私たちの大学のスタッフが望む方法です...彼らはまた、3日前までイテレータなしでコレクションを繰り返すように求めました:\ – tamir

答えて

2

addメソッドは、イテレータを作成した後にコレクションを変更します。代わりに、メンバ変数にイテレータを持つの

containsメソッド内に宣言:あなたの現在のコードと他の問題は、あなたのcontainsメソッドがイテレータを使い果たすことです

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

- あなたはを通して行ってきた後、かつて要素が含まれていないことが判明した場合、リセットされません。これは、次の要素が見つからないことを意味します。ローカル変数として宣言すると、この問題も修正されます。


はもちろん、あなたが本当にあなたが要素をプリントアウトしているという事実以外に、全くIterator必要はありません。 (私はあなたがデバッグのためにこれをやっていると思います;それは本当に有用ではありません)。

あなたは、単にCollection.containsを使用することができます。

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

ありがとうございます! – tamir

関連する問題