首先是我的代码:
public static List<AnagramFamily> assignFamilies(List<Word> theOriginalList) {
//Stores the list of anagram Families.
List<AnagramFamily> anagramList = new LinkedList<AnagramFamily>();
//TempList to store the word objects.
List<Word> tempList = new LinkedList<Word>();
ListIterator<Word> itr = theOriginalList.listIterator();
Word firstWord = theOriginalList.get(0);
int cnt = 0;
while(itr.hasNext()) {
Word secondWord = itr.next();
if (firstWord.getMyCanonical().equals(secondWord.getMyCanonical())) {
tempList.add(secondWord);
} else {
cnt++;
Collections.sort(tempList, new WordComparatorByDesecending());
anagramList.add(new AnagramFamily(tempList));
System.out.println(anagramList);
tempList.clear();
secondWord = itr.previous();
//create new anagram family
}
System.out.println("New First Word: " + firstWord + " Second Word: " + secondWord);
firstWord = secondWord;
}
System.out.println(anagramList);
return anagramList;
}
}
所以基本上这里发生的是我正在接受一个单词对象的链接列表:[abt,act,act,act,apt,apt,apt,at,ehy,ehy,ehy] Next I创建一个新的Anagram Family对象,它将以降序存储它。在名为anagramList的列表中,如果我想要,我可以迭代它并打印结果。
以下是正确的结果:[[abt] [act,act,act] [apt,apt,apt] [ehy,ehy,ehy]]
我的问题在这里我的输出看起来像[[ehy,ehy,ehy],[ehy,ehy,ehy],[ehy,ehy,ehy],[ehy,ehy,ehy]]
我的问题出在这行代码 anagramList.add(new AnagramFamily(tempList)); ,因为每次它都会覆盖最后一个对象。我怎么做才能覆盖呢?如果有人可以提供帮助那就太棒了!
public class AnagramFamily {
private List<Word> myFamilyList;
private int myFamilySize;
public AnagramFamily(List<Word> theFamilyList) {
myFamilyList = theFamilyList;
myFamilySize = myFamilyList.size();
}
public int getFamilySize() {
return myFamilySize;
}
public String toString() {
return myFamilyList.toString();
}
}
答案 0 :(得分:0)
最后的答案是tempList = new LinkedList<Word>();
这将保留一个新实例,而不是每次都覆盖该对象。