我的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...
}
}
}
我经历了几次类似的案件,但仍然不太了解。
答案 0 :(得分:2)
代码中最大的问题是tempWordsList
和aWordsList
引用同一个对象。您对tempWordsList
所做的任何更改都会在同一时间aWordsList
发生:
tempWordsList = aWordsList;
因此,myList
将拥有aWordList
的最后修改的多个副本:
myList.add(tempWordsList);
在循环的每次迭代中将相同的对象添加到myList
。
要制作aWordsList
和tempWordsList
,您需要使用副本替换作业,如下所示:
tempWordsList = new List<String>(aWordsList);
答案 1 :(得分:1)
应该是这样的:
Iterator<String> it = tempWordsList.iterator();
while(it.hasNext()){
String value = it.next();
// System.out.println("List Value:"+value);
if (value.equals(aWord)) {
it.remove();
}
}
答案 2 :(得分:1)
解决问题的方法如下,但这不是一个好的解决方法。
//解决
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...
}