我有一個HashMap是的Hashmap得到函數返回空值
public HashMap<String, ArrayList<Integer>> invertedList;
我告訴你我的觀察名單invertedList調試期間:
invertedList.toString(): "{ryerson=[0, 2, 3], 23=[3], award=[1], andisheh=[0, 2]}"
同樣觀察名單,當我進入:
invertedList.get("ryerson")
我得到null作爲結果,也在代碼中。正如你所看到的,「ryerson」已經在我的倒列表中作爲一個鍵了,我應該得到[0,2,3]!這裏發生了什麼?我很困惑!
我知道有一個ArrayList作爲值的問題,因爲我測試了整數作爲值,它工作正常,但仍然不知道如何解決它。我是java的新手,曾經與C#一起工作。
invertedList的完整代碼:
public class InvertedIndex {
public HashMap<String, ArrayList<Integer>> invertedList;
public ArrayList<String> documents;
public InvertedIndex(){
invertedList = new HashMap<String, ArrayList<Integer>>();
documents = new ArrayList<String>();
}
public void buildFromTextFile(String fileName) throws IOException {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
int documentId = 0;
while(true){
String line = bufferedReader.readLine();
if(line == null){
break;
}
String[] words = line.split("\\W+");
for (String word : words) {
word = word.toLowerCase();
if(!invertedList.containsKey(word))
invertedList.put(word, new ArrayList<Integer>());
invertedList.get(word).add(documentId);
}
documents.add(line);
documentId++;
}
bufferedReader.close();
}
測試代碼:
@Test
public void testBuildFromTextFile() throws IOException {
InvertedIndex invertedIndex = new InvertedIndex();
invertedIndex.buildFromTextFile("input.tsv");
Assert.assertEquals("{ryerson=[0, 2, 3], 23=[3], award=[1], andisheh=[0, 2]}", invertedIndex.invertedList.toString());
ArrayList<Integer> resultIds = invertedList.get("ryerson");
ArrayList<Integer> expectedResult = new ArrayList<Integer>();
expectedResult.add(0);
expectedResult.add(2);
expectedResult.add(3);
Assert.assertEquals(expectedResult, resultIds);
}
第一斷言工作正常,第二個,resultIds爲空。
請標記您的問題與您正在使用的語言。 – Barmar
你可以發佈你用來構建invertedList的代碼嗎? – user3360944
我改變了invertedList = new HashMap <>(); to invertedList = new HashMap>();問題仍然沒有解決。 –
Andi