Results 1 to 3 of 3
Hey everyone,
I am wrote a class called ScopedMap which is very similar to the HashMap class, only it has multiple layers (levels) which act like a scope (hence the ...
- 04-21-2007 #1Just Joined!
- Join Date
- Aug 2006
- Posts
- 59
HELP!! I dont see how i am continually getting a NullPointerException (java)!!!
Hey everyone,
I am wrote a class called ScopedMap which is very similar to the HashMap class, only it has multiple layers (levels) which act like a scope (hence the name). Unfortunately in one of my other class files which use it, I cannot seem to get around a null pointer exception when i call the get method. Here is the code:
I get the following error:Code:import java.util.HashMap; public class ScopedMap<K,V>{ private int nestingLevel = 0; private HashMap<Integer, HashMap<K,V>> scope = new HashMap<Integer, HashMap<K,V>>(); public ScopedMap(){ // does nothing } public void enterScope(){ nestingLevel++; if(scope.get(nestingLevel) == null){ scope.put(nestingLevel, new HashMap<K,V>()); } } public void exitScope(){ if(nestingLevel>0) // nesting level cannot be negative nestingLevel--; } public void put(K key, V value){ if(scope.get(nestingLevel) == null){ scope.put(nestingLevel, new HashMap<K,V>()); scope.get(nestingLevel).put(key, value); } else scope.get(nestingLevel).put(key, value); } public V getLocal(K key){ return scope.get(nestingLevel).get(key); } public V get(K key){ int temp = nestingLevel; while(temp>=0){ if(scope.get(temp).containsKey(key)){ // Here is line 40, where the exception occurs..... return scope.get(temp).get(key); } else temp--; } return null; } public int getNestingLevel(){ return nestingLevel; } }
Exception in thread "main" java.lang.NullPointerException
at ScopedMap.get(ScopedMap.java:40)
at Reader.main(Reader.java:4
ANY HELP WOULD BE GREATLY APPRECIATED!!!
Thanks,
Tom
- 04-22-2007 #2
Change this
With thisCode:if(scope.get(temp).containsKey(key)){ return scope.get(temp).get(key); }
That's happen if the "scope" has no value for key "temp", it will return "NULL", so it'll throw NullPointerException if you're trying to access it.Code:HashMap h = scope.get(temp); if (null != h && h.containsKey(key)) { return h; }
Hey, I get a greatly appreciationANY HELP WOULD BE GREATLY APPRECIATED!!!
.
- 04-22-2007 #3Just Joined!
- Join Date
- Aug 2006
- Posts
- 59
Thanks a bunch!!!!!!!


Reply With Quote