Hashmap get函数返回null

时间:2014-03-18 19:59:34

标签: java get null hashmap

我有一个

的hashmap
public HashMap<String, ArrayList<Integer>> invertedList;

我在调试期间在监视列表中显示了我的reverseList:

invertedList.toString(): "{ryerson=[0, 2, 3], 23=[3], award=[1], andisheh=[0, 2]}"

我输入时在同一个观察列表中:

invertedList.get("ryerson")

我的结果也是null,也在代码中。如你所见&#34; ryerson&#34;已经存在作为我的倒置列表中的一个键,我应该得到[0,2,3]!这里发生了什么?我很困惑!

我知道ArrayList存在一个问题,因为我测试了Integer作为值并且工作正常,但仍然不知道如何解决它。我是java的新手,曾经和C#一起工作。

reverseList的完整代码:

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);
}

第一个Assert工作正常,第二个,resultIds为空。

2 个答案:

答案 0 :(得分:2)

您的第一个断言测试invertedIndex.invertedList的值。第二个获取invertedList的值,而不是invertedIndex.invertedList的值。您可能在测试中定义了一个名称相同的地图,这与invertedIndex使用的地图不同。

答案 1 :(得分:2)

如果我正确阅读并正确假设,此测试函数位于InvertedIndex类中。我只做了那个假设,因为行

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

实际上应该是不可编译的,因为没有名为&#34; invertList&#34;的局部变量。

该行应为

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