Getting NullPointerException while putting data in hashtable

NullPointerException is thrown, when you try to access a method or variable of an instance of a class, but there is not really an instance present – so your object you want to work on is null.

Take for example this line:

                String ID = si.getInfo().get(i).getStId().toString();

This can go wrong in a couple of places:

                String ID = si.getInfo().get(i).getStId().toString();
        // Possible nulls     ^         ^      ^         ^
  • si can be null -> can’t invoke .getInfo() on it
  • the value returned by getInfo() is null -> can’t invoke .get(i) on it
  • the value returned by get(i) isnull-> can't invoke.getStd()` on it
  • the value returned by getStd() is null -> can’t invoke .toString() on it

All this would throw a NPE on the same line.

It is not nice, but you should to check all these for null, one by one. Depending on the business logic, you might want to handle some cases differently, e.g throw some kind of exception when one of them is null, etc…

if(si!=null) {
  StudentInfo info = si.getInfo; //using local variable to store value for readability
  if(info!=null) {

    //... and so on
  }
  else {
     throw new MyBusinessException("Info must not be null!");
  }
}

Also, this might be a fine choice to reduce the duplication in your code. You don’t have to write out all this si.getInfo().get(i).getStId(). each time: you can use local variables to store the in-between values of the navigation.

Hashtable

Hashtable is an old thing, you should not use for new stuff. It is deprecated. Instead of that, please use the Map interface and the appropriate implementation for this use case: the HashMap class. Also, through generics, it offers a lot more convenient syntax, leaving out casting.

Map<String, StudentList> myMap = new HashMap<String, StudentList>();
.... 

myMap.put(id, studentList);

Also recommended for consideration

Leave a Comment