[英]How to remove List iteration without ConcurrentModificationException
我的allWordsList
類似於: [aaa, bbb, ccc, ddd, eee]
如何進行復印( tempWordsList
的) allWordsList
在
for (String aWord : aWordsList)
沒有迭代項(即實現[bbb, ccc, ddd, eee]
,然后[aaa, ccc, ddd, eee]
等)?
public class Anagrams {
List<String> allWordsList = new ArrayList<String>();
List<List<String>> myList = new ArrayList<List<String>>();
List<String> tempWordsList = new ArrayList<String>();
public Anagrams(String allWords) {
getWordsList(allWordsList, allWords); // getting List to copy here
getAnagramWordsList(allWordsList);
}
private void getAnagramWordsList(List<String> aWordsList) {
for (String aWord : aWordsList){
//tempWordsList.clear();
tempWordsList = aWordsList;
for (Iterator<String> iterator = tempWordsList.iterator(); iterator.hasNext();) {
String string = iterator.next();
if (string == aWord) {
// Remove the current element from the iterator and the list.
iterator.remove();
}
}
myList.add(tempWordsList);
System.out.println(aWordsList);
System.out.println(tempWordsList); //before error both lists are without first item...
}
}
}
我經歷了幾個類似的案例,但仍然不太了解。
您的代碼中最大的問題是tempWordsList
和aWordsList
引用同一對象。 您對tempWordsList
任何更改aWordsList
在同一確切時間發生在aWordsList
上:
tempWordsList = aWordsList;
因此, myList
會有最后修改的多個副本aWordList
:
myList.add(tempWordsList);
在循環的每次迭代中將相同的對象添加到myList
中。
為了制作aWordsList
和tempWordsList
您需要用一個副本替換賦值,如下所示:
tempWordsList = new List<String>(aWordsList);
應該是這樣的:
Iterator<String> it = tempWordsList.iterator();
while(it.hasNext()){
String value = it.next();
// System.out.println("List Value:"+value);
if (value.equals(aWord)) {
it.remove();
}
}
解決問題的方法如下,但這並不是一個好的解決方法。
//解決
private void getAnagramWordsList(List<String> aWordsList) {
List<Integer> toRemove = new ArrayList<Integer>();
for (String aWord : aWordsList){
//tempWordsList.clear();
tempWordsList = aWordsList;
for (int i = tempWordsList.size()-1; i > 0; i--) {
if (string.equals(tempWordsList.get(i)) {
toRemove.add(i);
}
}
for(int idx = 0; idx < toRemove.size(); idx++)
tempWordsList.remove(idx);
myList.add(tempWordsList);
System.out.println(aWordsList);
System.out.println(tempWordsList); //before error both lists are without first item...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.