HashMap assignment and null pointer exception
Here is some simple piece of code:
Code:
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
public class InvertedIndex implements Serializable {
private HashMap<String, ArrayList<Integer>> index;
private static final long serialVersionUID = 1L;
/**
* @param token
* @param id
*/
public void add(String token, int id) {
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(id);
System.out.println(al.toString());
System.out.println(token);
index.put(token, al);
}
public void print(){
System.out.println(index.toString());
}
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) {
String[] words = new String[4];
words[0] = "one";
words[1] = "two";
words[2] = "other";
words[3] = "two";
InvertedIndex ii = new InvertedIndex();
for(int i = 0; i< words.length; i++){
ii.add(words[i],i);
}
}
}
When I execute it, I get a null pointer exception (which is by far the least informative exception I've seen in Java :p ) and I can't understand why. The exception is triggered when the index.put(token, al); is executed.
Can you please guide me?