0

I am constructing a FrequencyBag that will take something like an Integer, String or Character, and it will take the data and pair it with its frequency.

For example:

 FrequencyBag<Integer> fb = new FrequencyBag<Integer>();

  fb.add(cat);
  fb.add(dog);
  fb.add(horse);
  fb.add(cat);
  fb.add(cat);

will look like

 (cat,3) ---> (dog,1) ---> (horse, 1)

My method getMaxFreq() has no problem getting the max frequency (which is 3 for the example above) when the bag contains elements, but when I try to return the value 0 for an empty null FrequencyBag() I get this error.

"Exception in thread "main" java.lang.NullPointerException" "FrequencyBag$Node.access$1(FrequencyBag.java:8)"

Here is my method below:

    public int getMaxFreq() {

    Node<T> currentNode = firstNode;
    Node<T> nextNode = firstNode.next;

    int compareVal = nextNode.freq;
    int maxVal = currentNode.freq;

    if (currentNode == null) {
        maxVal = 0;
        return maxVal;
    }

    while (nextNode.next != null) {

        if (maxVal < compareVal) {
            maxVal = compareVal;
        }

        else {
            // Do nothing
        }

        currentNode = currentNode.next;
        nextNode = nextNode.next;
    }

    if (nextNode.next == null) {
        if (maxVal < nextNode.freq) {
            maxVal = nextNode.freq;
        } else {
            // Do nothing
        }

        return maxVal;
    }

    return maxVal;

}

Instead of getting a null pointer error, I want to do this when I create an empty bag and call my getMaxFreq() method:

 FrequencyBag<Integer> emptyBag = new FrequencyBag<Integer>();

 System.out.println("Output: " + emptyBag.getMaxFreq());

 Output: 0
user3716274
  • 25
  • 1
  • 4
  • 1
    What's holding you back? – Sotirios Delimanolis Sep 27 '14 at 01:44
  • I am not exactly sure why I am getting a null pointer exception. – user3716274 Sep 27 '14 at 01:46
  • My if(currentNode == null) statement should have handled that, but I still get an error. – user3716274 Sep 27 '14 at 01:46
  • If you are not sure where a null pointer exception occurs, you can make possible null values explicit by using an option type, such as the `Optional` type defined by Guava: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Optional.html. It's generally good to not wildly pass around null values. But to simply discover where your null pointer exception happens, you can also just step through your code with the debugger. – Kulu Limpa Sep 27 '14 at 01:54

1 Answers1

0

You may want to try first checking if currentNode == null before trying to dereference 'currentNode' on line 7 (it seems), this line -> int maxVal = currentNode.freq;

Otherwise you are trying to dereference a null pointer which is was is liking throwing that nullPointerException

The same applies to 'nextNode'