问题
I have a hashmap which is
public HashMap<String, ArrayList<Integer>> invertedList;
I show you my invertedList in watch list during debugging:
invertedList.toString(): "{ryerson=[0, 2, 3], 23=[3], award=[1], andisheh=[0, 2]}"
In the same watch list when I enter:
invertedList.get("ryerson")
I get null as result, also in the code. As you can see "ryerson" is already there as a key in my invertedList and I should get [0, 2, 3] as a result!!! What is happening here? I'm so confused!
I know there is a problem with ArrayList as values, because I tested Integer as values and it worked fine, but still don't know how to solve it. I am new to java, used to work with C#.
The complete code of 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();
}
The test code:
@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);
}
The first Assert works fine, the second one, resultIds is null.
回答1:
If I'm reading this right, and assuming correctly, this test function is inside the InvertedIndex class. I only make that assumption because the line
ArrayList<Integer> resultIds = invertedList.get("ryerson");
should actually be uncompilable as there is no local variable called "invertedList".
That line should read
ArrayList<Integer> resultIds = invertedIndex.invertedList.get("ryerson");
回答2:
Your first assert tests the value of invertedIndex.invertedList
. The second one gets a value from invertedList
, and not from invertedIndex.invertedList
. You've probably defined a map with the same name in your test, which is different from the one used by invertedIndex
.
来源:https://stackoverflow.com/questions/22489756/hashmap-get-function-returns-null