我的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
上:
tempWordsList = aWordsList;
因此,
myList
将具有aWordList
的最后修改的多个副本:myList.add(tempWordsList);
在循环的每次迭代中将相同的对象添加到
myList
。为了制作
aWordsList
和tempWordsList
,您需要用一个副本替换分配,如下所示:tempWordsList = new List<String>(aWordsList);