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