This discussion is archived
2 Replies Latest reply: Nov 21, 2012 1:02 AM by gimbal2 RSS

NullPointerException while updating a TreeMap<Integer, Integer>

975389 Newbie
Currently Being Moderated
Dear All,

I have a strange problem updating an empty TreeMap datastructure.
I am trying to create a TreeMap map and put key-value pairs into it. It gives me a NullPointerException at the line -- if(!quals.containsKey(bq)){
I am checking if the int variable is present in the keys of quals (TreeMap) and then updating accordingly.

The snippet follows:

public class Test{
private TreeMap<Integer, Integer> quals;
public void Test(){
this.quals = new TreeMap<>();
}

public static void void main(){
String qual = "-)(*(%"'%.--)&./,*,&#.,'')+/-///+/)/,)/,)-/.//.+-..&)##";
for(int i = 0; i < qual.length(); ++i){
// deriving int value of a char
int bq = qual.charAt(i);
if(!quals.containsKey(bq)){
quals.put(new Integer(bq), 1);
}
else{
int count = quals.get(bq);
quals.put( new Integer(bq), ++count);
}
}
}
  • 1. Re: NullPointerException while updating a TreeMap<Integer, Integer>
    TPD-Opitz-Consulting-com Expert
    Currently Being Moderated
    Welcome to the forum.

    please read this to make better posts: https://wikis.oracle.com/display/Forums/Forums+FAQ
    -----


    I'd say your code does not compile at all.
    Because you cannot acces the non static variable <tt>quals</tt> from the static method <tt>main</tt>. But maybe you forgot to type the static key word in your line 2 in this post?

    If so:
    you initialize the reference <tt>quals</tt> in the constructor (wich BTW is a bad practice). But since you do not create an Object of that class your reference never points to an actial map but to <b>null</b>.

    So the NPE you're facing is not strange at all... ;o)

    bye
    TPD
  • 2. Re: NullPointerException while updating a TreeMap<Integer, Integer>
    gimbal2 Guru
    Currently Being Moderated
    TPD Opitz-Consulting com wrote:
    So the NPE you're facing is not strange at all... ;o)
    Unless you hardly know any Java at all of course. But that's not a problem fixed by posting in a forum, that's fixed by studying using a proper resource (a good book or even following a course!) and lots of experimenting.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points