我必須使用TreeMap執行同義詞字典。 TreeMap的類型爲<Word, ArrayList<Word>>
。這意味着對於由Word代表的每個關鍵字,將會有一個同義詞列表。當我想列出字典的內容時,通過使用下面的方法,我發現返回的ArrayList爲null。我能做什麼?我試圖追蹤代碼,但我似乎沒有發現錯誤。 方法是:由TreeMap返回的空ArrayList Java
public String listContent() {
Set set = wordList.keySet();
Iterator it = set.iterator();
String result = new String();
ArrayList<Word> words = new ArrayList<Word>();
while (it.hasNext()) {
Word temp = (Word) it.next();
words = wordList.get(temp);
if (words != null) {
Iterator it2 = words.iterator();
result += temp.getContent();
result += " - ";
int size = words.size();
while (it2.hasNext()) {
result += ((Word) it2.next()).getContent();
if (size != 1)
result += ", ";
size--;
}
result += "\n";
}
}
return result;
}
由wordList.get(TEMP)返回的ArrayList中爲空一段插入的元件。我檢查了手表,但在那裏,他們沒有。我該怎麼辦 ?
單詞表是一個TreeMap<Word, ArrayList<Word>>;
編輯 - 在addWord方法
public void addWord(String content1, String content2)
{
Word w1 = new Word(content1);
Word w2 = new Word(content2);
Set set = wordList.entrySet();
Iterator it = set.iterator();
boolean ok=false;
while(it.hasNext())
{
Map.Entry<Word,ArrayList<Word>> temp = (Map.Entry<Word,ArrayList<Word>>) it.next();
if(temp.getKey().getContent().matches(content1))
{
ArrayList<Word> words = temp.getValue();
Iterator it2 = words.iterator();
if(words.isEmpty()) words.add(w2);
else
{
boolean ok2=true;
while(it2.hasNext())
{
Word tempy = (Word) it2.next();
if(tempy.getContent().equals(content2))
{
ok2=false;
break;
}
}
if(ok2) words.add(w2);
}
ok=true;
}
}
if(!ok) {
ArrayList<Word> tempys = new ArrayList<Word>();
tempys.add(w2);
wordList.put(w1,tempys);
}
}
EDIT 2 - 詞類
public class Word implements Serializable,Comparable {
private String content;
public Word (String content)
{
this.content = content;
}
public void setContent(String content)
{
this.content=content;
}
public String getContent()
{
return content;
}
@Override
public int compareTo(Object o) {
if(((Word)o).getContent().equals(this.getContent())) return 0;
return 1;
}
}
想要編輯,但你更快 –
你可以顯示代碼你在哪裏填充'TreeMap'? – Tudor
同時向我們展示Word類的代碼。無論如何,爲什麼你需要這個類,爲什麼不使用String?會有更少的事情可能出錯。 – ZeroOne