-3

I have two hashMaps :

private HashMap<String, HashMap<String, Integer>> attributesCountPerCategory;

and

private HashMap<String, Integer> attributesCount;

I also have the method:

public void increaseAttributes(String attr, String category){
    HashMap<String, Integer> attributes = this.attributesCountPerCategory.get(category);
    if (attributes == null) {
        this.attributesCountPerCategory.put(category, new HashMap<String, Integer>());
        attributes = this.attributesCountPerCategory.get(category);
    }

    Integer c = attributes.get(attr);
    if(c == null){
        attributes.put(attr, 0);
        c = attributes.get(attr);
    }
    attributes.put(attr,c++);

    Integer c2 = this.attributesCount.get(attr);
    if(c2 == null){
        this.attributesCount.put(attr,0);
        c2 = this.attributesCount.get(attr);            
    }
    this.attributesCount.put(attr,c2++);        
}

So when I am calling this method a NullPointerException is thrown even though I am checking for null values in object references. The exception is thrown in the below line:

HashMap<String, Integer> attributes = this.attributesCountPerCategory.get(category);

What could be the problem?

MinnuKaAnae
  • 1,646
  • 3
  • 23
  • 35

1 Answers1

1

this is because in this line

HashMap<String, Integer> attributes = this.attributesCountPerCategory.get(category);

attributesCountPerCategory has not been initialized. This is why it is null.

to fix either do

private HashMap<String, HashMap<String, Integer>> attributesCountPerCategory = new HaspMap<String, HashMap<String, Integer>> ();

or initialise it at some other point prior to calling it

Vardaan Sharma
  • 1,125
  • 1
  • 10
  • 21