我的 allWordsList
类似于:[aaa, bbb, ccc, ddd, eee]
如何在
中创建allWordsList
的副本 (tempWordsList
)
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
上:
tempWordsList = aWordsList;
因此,myList
将拥有 aWordList
最后修改的多个副本:
myList.add(tempWordsList);
在循环的每次迭代中将相同的对象添加到 myList
中。
为了制作 aWordsList
和 tempWordsList
,您需要用副本替换分配,如下所示:
tempWordsList = new List<String>(aWordsList);
关于java - 如何在没有 ConcurrentModificationException 的情况下删除 List 迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33503052/