2014-03-18 72 views
0

我有一個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爲空。

+0

請標記您的問題與您正在使用的語言。 – Barmar

+0

你可以發佈你用來構建invertedList的代碼嗎? – user3360944

+0

我改變了invertedList = new HashMap <>(); to invertedList = new HashMap >();問題仍然沒有解決。 – Andi

回答

2

如果我正在閱讀這個權利,並假設正確,這個測試函數在InvertedIndex類中。我只能做這樣的假設,因爲線

ArrayList<Integer> resultIds = invertedList.get("ryerson"); 

實際上應該是不可編譯的,因爲沒有所謂的「invertedList」局部變量。

這行應爲

ArrayList<Integer> resultIds = invertedIndex.invertedList.get("ryerson"); 
2

您首先聲明測試invertedIndex.invertedList的值。第二個從invertedList得到一個值,而不是從invertedIndex.invertedList。您可能已經在測試中定義了一個具有相同名稱的地圖,該地圖與invertedIndex使用的名稱不同。