NullPointerException while iterating over Binary Tree - java

Now I'm not sure anybody can really help me with this, since it's a pretty sizable amount of code to go through, but any help would be greatly appreciated. Here is my relevant code:
public class BTree implements Iterable<String> {
/** Left child */
BTree left;
/** Right Child */
BTree right;
/** Comparator to use for sorting */
Comparator<String> comp;
/** Parent node */
BTree parent;
/** String stored in this leaf */
String s;
/** # of iterators currently working on it */
int active = 0;
/** Size of the BTree */
int size;
public void build(Iterable<String> iter, int numStrings) {
if (this.active > 0) {
throw new ConcurrentModificationException();
}
else {
Iterator<String> itr = iter.iterator();
while (numStrings != 0 && itr.hasNext()) {
String s = itr.next();
if (!this.contains(s)) {
this.insert(s);
this.size++;
numStrings--;
}
}
}
}
/**
* Inserts the string into the given BTree
* #param str - String to insert
*/
private void insert(String str) {
if (this.s.equals("")) {
this.s = str;
}
else if (this.comp.compare(str, this.s) > 0) {
if (this.right == null) {
BTree bt = BTree.binTree(this.comp);
bt.s = str;
this.right = bt;
bt.parent = this;
}
else {
this.right.insert(str);
}
}
else if (this.comp.compare(str, this.s) < 0) {
if (this.left == null) {
BTree bt = BTree.binTree(this.comp);
bt.s = str;
this.left = bt;
bt.parent = this;
}
else {
this.left.insert(str);
}
}
}
private class BTreeIterator implements Iterator<String> {
/** Current BTree being iterated over */
BTree current;
/** How many next() calls have there been */
int count;
/** Size of the BTree */
int max;
/** Constructor for BTreeIterator
* #param current
*/
BTreeIterator(BTree current) {
this.current = current;
this.count = 0;
this.max = current.size;
active++;
}
/** Returns true if there is another string to iterate over
* #return boolean
*/
public boolean hasNext() {
if (this.count != this.max) {
return true;
}
else {
active--;
return false;
}
}
/**
* Returns the next string in the iterator
* #return String
*/
public String next() {
if (this.count == 0) {
this.count++;
current = this.current.getLeftMost();
if (this.current.s.equals("")) {
throw new NoSuchElementException();
}
return this.current.s;
}
else if (this.current.right != null) {
this.current = this.current.right.getLeftMost();
this.count++;
return this.current.s;
}
else {
BTree tree = this.current;
while (tree.parent.right == tree) {
tree = tree.parent;
}
this.current = tree.parent;
this.count++;
return this.current.s;
}
}
/** Throws an exception since we aren't removing anything from the trees
*/
public void remove() {
throw new UnsupportedOperationException();
}
}
}
}
The Exception gets thrown at the while (tree.parent.right == tree) line in the next() method of the iterator. The funny thing is, my code has worked just fine with a comparator comparing lexicographically and reverse lexicographically sorting through a file of 24000 words. It only throws the exception when using the following comparator:
class StringWithOutPrefixByLex implements Comparator<String> {
/**
* compares o1 and o2
* #param o1 first String in comparison
* #param o2 second String in comparison
* #return a negative integer, zero, or a positive integer
* as the first argument is less than, equal to, or
* greater than the second.
*/
public int compare(String o1, String o2) {
String s1, s2;
if(o1.length() > 4){
s1 = o1.substring(3);
}
else {
s1 = o1;
}
if(o2.length() > 4){
s2 = o2.substring(3);
}
else {
s2 = o2;
}
return s1.compareTo(s2);
}
}
Even weirder, it works fine with that comparator for the same file up to 199 words, but as soon as I have it build up to 200 words it breaks.
EDIT: I have determined that the Exception is due to the code trying to reference tree.parent.right while tree.parent is null, but I can't figure out WHY it's trying to do that. As far as I can tell, my code should never try to call a null tree.parent, as explained by my comment below.

Well, you do not actually show enough of your code, but, what about the root node of your BTree? What is the value of BTree.parent in the root node? null?
If the root node has a null parent, then, in this while loop, it is likely that :
while (tree.parent.right == tree) {
tree = tree.parent;
}
... will get to the root node, the tree will be set to tree.parent, which is null, and then the while loop test will fail because tree.parent.right will attempt to dereference a null pointer.

Related

Right Rotation Linked List Recursively

I need to create a method to rotate or shift elements in a LinkedList which is called ListItem for my program to the right recursively. For example, I have the List 1->2->3->4 after the method it is 4->1->2->3. The Method should return the rotated List.
So, this is what could be helpful for the method:
public class ListItem<T>
{
public T key;
public ListItem<T> next;
/**
* Constructor of this Class
*
* #param key
* the key of the ListItemAbstract
*/
public ListItem(T key)
{
this.key = key;
}
#SuppressWarnings("unchecked")
#Override
public boolean equals(Object obj)
{
if (obj == null || obj.getClass() != this.getClass())
return false;
if (this.key == null && ((ListItem<T>) obj).key == null)
return true;
if (this.key != null && this.key.equals(((ListItem<T>) obj).key))
{
if (this.next == null)
if (((ListItem<T>) obj).next == null)
return true;
else
return false;
return this.next.equals(((ListItem<T>) obj).next);
}
else
return false;
}
/**
* This methode returns the Element on the given position.
*
* #param pos
* the position to return the key from. Position 1 means the current element
* #return the key of the element at pos
* #throws IllegalArgumentException
* if the position ist not in the list
*/
public T get(int pos) throws IllegalArgumentException
{
// recursion stop
if (pos == 1)
{
return this.key;
}
else if (pos > 1)
{
// recursion start: call this method again for the next element of the list,
// but check for NullpointerException first
if (next != null)
{
return next.get(pos - 1);
}
else
{
//
throw new IllegalArgumentException("the index is greater than the number of elements in this list");
}
}
else
{
throw new IllegalArgumentException("the position is less than 1, but must be equal to or higher than 1");
}
}
/**
* This method returns the size of the List
*
* #return the size of this list
*/
public int getSize()
{
if (this.key == null && this.next == null)
{
// recursion stop: no next element and this key is null -> don't add it to the size
return 0;
}
else if (this.next == null) // deleting this if-case causes a NullpointerException
{
// recursion stop: no next element, but this key is not null -> add it to the size
return 1;
}
else
{
// recursion start: recall this method for the next element and increase the size by one
return this.next.getSize() + 1;
}
}
/**
* Inserts an key into this list.
*
* #param key
* the key to insert.
* #throws IllegalArgumentException
* if key is null
*/
public void insert(T key) throws IllegalArgumentException
{
if (key == null)
{
throw new IllegalArgumentException("Cannot insert null");
}
else if (this.key == null && this.next == null)
{
this.key = key;
}
else
{
ListItem<T> p = this;
while (p.next != null)
{
p = p.next;
}
p.next = new ListItem<T>(key);
}
}
}
This is what I have so far for the method:
/**
* The method shifts the elements of the List to the right.
*
* #param lst
* the list to work on
* #return the new list
*/
public ListItem<T> ringShiftRight(ListItem<T> lst) {
if (lst == null) {
return null;
}
if (lst.next == null) {
return lst;
}
// TODO Here I have no Idea how to create the method any further
}
Traverse ListItem till last item and that will become ListItem to be returned. Add input lstto next of next.
ListItem<T> returnList = this.ringShiftRight(lst.next);
lst.next.next = lst;
lst.next = null;
return returnList;

Why is the remove() method in my customized LinkedList not working properly?

I'm sorry if this is a very long code, but the only problem is the remove() method in the LinkedList Class, and I've been struggling on this code for hours and couldn't seem to find a solution. Whenever I input ADD 456 for the main method, instead of printing
0+6+5+4
RESULT 15
I keep on getting
0+6+6+4
RESULT 16
That means either the remove() or insert() method went wrong, but when I checked the input of the insert() method, 5 was properly inserted when it had to. So I was wondering which part of the remove() method went wrong, and how I could solve it. Thanks.
These are the interfaces.
Interface Stack.
package ds.stack;
public interface Stack<E> {
/*
* Removes all of the elements in this stack.
*/
public void clear();
/*
* Pushes an item onto the top of this stack.
*
* #param item
* the item to be pushed onto this stack
*/
public void push(E item);
/**
* Removes the item at the top of this stack and returns that item as the
* value of this method.
*
* #return the item at the top of this stack, or null if this stack is empty
*/
public E pop();
/**
* Returns the number of elements in this stack.
*
* #return the number of elements in this stack
*/
public int length();
/**
* Returns true if this stack contains no elements.
*
* #return true if this stack contains no elements
*/
public boolean isEmpty();
}
Interface List.
package ds.list;
public interface List<E> {
/**
* Removes all of the elements from this list.
*/
public void clear();
/**
* Inserts the specified element at the specified position in this list.
*
* #param pos
* index at which the specified element is to be inserted
* #param item
* element to be inserted
*/
public void insert(int pos, E item);
/**
* Removes the element at the specified position in this list. Shifts any
* subsequent elements to the left (subtracts one from their indices).
* Returns the element that was removed from the list.
*
* #param pos
* the index of the element to be removed
* #return the element previously at the specified position
*/
public E remove(int pos);
/**
* Returns the number of elements in this list.
*
* #return the number of elements in this list.
*/
public int length();
/**
* Returns the element at the specified position in this list.
*
* #param pos
* index of the element to return
* #return the element at the specified position in this list
*/
public E getValue(int pos);
}
Here is my LinkedList Class
package ds.list;
public class LinkedList<E> implements List<E> {
private E element;
private LinkedList<E> next;
private LinkedList<E> head;
private LinkedList<E> tail;
private LinkedList<E> curr;
public int cnt=0; //length of the list
/*
* constructors below
*/
public LinkedList() { //The very initial constructor
curr = tail = head = this;
}
public LinkedList(LinkedList<E> nextval) { //when you start making more bundles
next = nextval;
}
public void setNext(LinkedList<E> nextval) {
next = nextval;
}
public void goNext() {
curr = next;
} // curr becomes the next bundle
public void setValue(E item) {
element = item;
}
#Override
public void clear() {
tail = head = new LinkedList<E>();
next = null;
cnt = 0;
}
#Override
public void insert(int pos, E item) {
if(pos<0||pos>cnt+1) {
return;
}
if(pos==0) {
curr = head;
head = new LinkedList<E>(curr);
curr = head;
curr.setValue(item);
}
curr = head;
for(int i=0;i<pos-1;i++) {
goNext();
} //curr points right before the index of pos
LinkedList<E> temp = curr.next;
curr.setNext(new LinkedList<E>(temp));
curr.goNext();
curr.setValue(item);
cnt++;
}
#Override
public E remove(int pos) {
if(pos<0||pos>cnt)
return null;
curr = head;
if(cnt==1) {
E it = element;
curr = head = tail = null;
cnt--;
return it;
}
for(int i=0;i<pos-1;i++) {
goNext();
}
E it = next.element;
curr.setNext(next.next);
cnt--;
return it;
}
#Override
public int length() {
return cnt;
}
#Override
public E getValue(int pos) {
if(pos<0||pos>cnt)
return null;
curr = head;
for(int i=0;i<pos-1;i++) {
goNext();
}
return next.element;
}
}
And this is my LinkedStack Class, utilizing the LinkedList Class
package ds.stack;
import ds.list.LinkedList;
public class LinkedStack<E> implements Stack<E> {
private LinkedList<E> stack = new LinkedList<E>();
#Override
public void clear() {
stack.clear();
}
#Override
public void push(E item) {
if(stack.cnt == 0) {
stack.setValue(item);
stack.cnt++;
return;
}
stack.insert(stack.length(),item);
}
#Override
public E pop() {
if(stack.length()==0) {
return null;
}
else {
return stack.remove(stack.length()-1);
}
}
#Override
public int length() {
return stack.length();
}
#Override
public boolean isEmpty() {
if(stack.length()==0)
return true;
return false;
}
}
Then this is my BabyCalculator Class that uses the LinkedStack Class
package ds.test;
import ds.stack.LinkedStack;
import ds.stack.Stack;
public class BabyCalculator {
Stack<Character> stack = new LinkedStack<Character>();
private int value=0;
public int murmurAdd(String polynomial) {
char[] charPol=polynomial.toCharArray();
int count=0;
for(int i=0;i<polynomial.length();i++) {
if(!(Character.isDigit(charPol[i])))
count++;
} // This counts the total number of ( and )s.
int numOf=count/2;
if (numOf==0) {
for(int i=0;i<polynomial.length();i++) {
stack.push(charPol[i]);
}
}
else {
for(int i=0;i<numOf;i++) {
int num1=0, num2 = 0; //will become the index of last ( and first )
for(int j=0;j<polynomial.length();j++) {
if(charPol[j]=='(')
num1 = j;
if(charPol[j]==')') {
num2 = j;
break;
}
}
for(int index=num1+1;index<num2;index++) {
stack.push(charPol[index]);
}
StringBuilder polytemp = new StringBuilder(polynomial);
polynomial=polytemp.replace(num1, num2+1, "").toString();
}
if(polynomial.length()>0) {
charPol = polynomial.toCharArray();
for(int i=0;i<polynomial.length();i++) {
stack.push(charPol[i]);
}
}
}
System.out.print(value);
while(!(stack.isEmpty())) {
Character a = stack.pop();
System.out.println(" a is "+a);
value += Character.getNumericValue(a);
System.out.print("+"+a);
}
System.out.println();
return value;
}
public int getValue() {
// TODO Implement this method
return value;
}
public void setValue(int newValue) {
// TODO Implement this method
value = newValue;
}
}
Finally, the main() method that uses BabyCalculator.
package ds.test;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
BabyCalculator babyCalculator = new BabyCalculator();
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String command = sc.next();
if ("ADD".equals(command)) {
String equation = sc.next();
babyCalculator.murmurAdd(equation);
System.out.println("RESULT "+babyCalculator.getValue());
// TODO
} else if ("SHOW".equals(command)) {
System.out.println("VALUE "+babyCalculator.getValue());
// TODO
} else if ("CLEAR".equals(command)) {
babyCalculator.setValue(0);
System.out.println("VALUE CLEARED");
// TODO
} else if ("SET".equals(command)) {
int newValue = sc.nextInt();
babyCalculator.setValue(newValue);
System.out.println("VALUE SET TO "+babyCalculator.getValue());
// TODO
} else if ("EXIT".equals(command)) {
System.out.println("FINAL VALUE "+ babyCalculator.getValue());
return;
// TODO
}
}
sc.close();
}
}
EDIT : When I tried ADD (2345), the result was
0+5+5+5+2
RESULT 17
Which means 5 kept popping out only until it was time for 2 to pop out. Why does this keep happening?I'm assuming it's a deep pointing issue in LinkedList class.
Well, I can say with certainty that your LinkedList is not correctly implemented. You need to do unit testing of your foundational classes before you build on top of them. A basic test involving nothing more than inserting a few elements into position 0 and then trying to get the value of items in positions 0, 1, and 2 fails.
This was a basic test I wrote and it fails with NullPointerException.
LinkedList<String> list = new LinkedList<>();
list.insert(0, "A");
list.insert(0, "B");
list.insert(0, "C");
System.out.println(list.getValue(0));
System.out.println(list.getValue(1));
System.out.println(list.getValue(2));
Add more logging throughout your code, use a debugger, implement toString methods on your classes to help you find the problems.
I can tell you that your LinkedList method getValue does not work as intended. To get my test above to work I had to change from this:
for(int i=0;i<pos-1;i++) {
goNext();
}
return next.element;
to this:
for (int i = 0; i < pos; i++) {
goNext();
}
return curr.element;
The reason is because "next" refers to the next element of whatever LinkedList you called getValue on, not the next element after the current one.
I can also tell you that you have a similar bug in your goNext method of LinkedList:
public void goNext() {
curr = next;
}
should be:
public void goNext() {
curr = curr.next;
}
There are almost certainly more issues with this class, so I highly recommend you thoroughly test and debug it as this will probably solve many of your problems.
I see more issues than one. The insert is wrong, the remove is wrong (you can validate) by calling ADD twice in the same run.
One such issue is in insert I changed your code as below:
//LinkedList<E> temp = curr.next;
//curr.setNext(new LinkedList<E>(temp));
LinkedList<E> temp = new LinkedList<E>(curr.next);
temp.setValue(curr.element);
And removed the loop
for(int i=0;i<pos-1;i++) {
goNext();
}
in remove method Atleast add test works. But you have more problems at hand. I didn't test much of other usecases.

Java Iterator for circular linked list

I've created a CircularLinkedList class, instead of using the util LinkedList class. The problem is based off of the Josephus problem, stating that for a circle of 20 people, each 12th person is to be killed until it is determined which position the survivor will be left standing in (using an Iterator). I'm confused as to how I could use an Iterator with this problem, since I'm using my own class instead of LinkedList, which already has an iterator() method so that I could declare an Iterator like this:
Iterator<E> iter = cll.iterator();
I have no idea how I would write my own Iterator method, and I feel like I have to be over thinking this. Any help is appreciated! I can post my code if it would clear anything up that I forgot to mention
I'm still stuck on this, so I figured I'd post my code to see if anyone can help. It's a lot, so I apologize.
Itr class (Iterator)
import java.util.Iterator;
public class Itr<E> extends CircularLinkedList<E> implements Iterator<E>
{
/** the size of the list */
private int size = 0;
/** for the hasNext() method for Iterator */
private int nextNode = 0;
/** two Nodes used for next() method for Iterator */
private Node<E> lastReturned = null;
private Node<E> nextUp;
/** part of the Iterator implementation */
public boolean hasNext()
{
return nextNode < size;
}
/** part of the Iterator implementation */
public E next()
{
lastReturned = nextUp;
nextUp = nextUp.getNext();
nextNode++;
return lastReturned.data;
}
/** part of the Iterator implementation */
public void remove()
{
Node<E> lastNext = lastReturned.getNext();
if (lastReturned == null)
nextUp = lastNext;
else
nextNode--;
lastReturned = null;
}
}
Josephus class
public class Josephus<E>
{
public static void main(String[] args)
{
CircularLinkedList cll = new CircularLinkedList();
Itr iter = cll.iterator();
int lastMan = 0;
int n = 20;
int passes = 12;
while(n > 1)
{
iter.next();
for(int i = 0; i < n; i += passes)
{
iter.hasNext();
iter.remove();
if(n == 1)
lastMan = n;
}
}
System.out.println("Survior: " + lastMan);
}
}
CircularLinkedList class
public class CircularLinkedList<E>
{
public class Node<E>
{
/* data value **/
public E data;
/* the link **/
private Node<E> next = null;
/** constructs a Node with given data and link
* #param data the data value
* #param next the link
*/
public Node(E data, Node<E> next)
{
this.data = data;
this.next = next;
}
/** construct a Node with given data value
* #param data the data value
*/
public Node(E data)
{
this.data = data;
}
/** return the data value of a Node
* #return the data value
*/
public E getData()
{
return data;
}
/** set the next Node in a list
* #param append the data value that the new Node will contain
*/
public void setNext(Node append)
{
next = append;
}
/** return the next Node
* # return the next Node
*/
public Node<E> getNext()
{
if(current.next == null)
current.next = current;
return next;
}
}
/** a reference into the list */
private Node<E> current = null;
/** the size of the list */
private int size = 0;
/** helper methods */
/** remove the first occurance of element item.
* #param item the item to be removed
* #return true if item is found and removed; otherwise, return false.
*/
public void removeItem(E item)
{
Node<E> position = current;
Node<E> nextPosition1,
nextPosition2;
while (position.next != null)
{
if(position.getNext().getData().equals(item))
{
nextPosition1 = position.getNext();
nextPosition2 = nextPosition1.getNext();
position.setNext(nextPosition2);
}
else
{
position = position.getNext();
}
}
}
/** set the first Node in a list
* #param append the data value that the new Node will contain
*/
public void addFirst(E append)
{
current = new Node<E>(append, current);
size++;
}
/** add a new Node as the last in the List
* #param data value of the new Node
*/
public void addNext(E value)
{
// location for new value
Node<E> temp = new Node<E>(value,null);
if (current != null)
{
// pointer to possible tail
Node<E> finger = current;
while (finger.next != null)
{
finger = finger.next;
}
finger.setNext(temp);
} else current = temp;
size++;
}
/** return the data value of the fourth Node in the list
* #return the data value
*/
public E printFourth()
{
current.next.next.next = current;
return current.next.next.next.getData();
}
/** return the size of the LinkedList
* #return the size
*/
public int size()
{
return size;
}
public E get(int index)
{
Node<E> temp = null;
for(int i = 0; i < index; i++)
{
temp = current.next;
System.out.print(temp.getData() + " ");
}
return temp.getData();
}
public Itr<E> iterator()
{
return new Itr<E>();
}
#Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("[");
Node<E> aux = this.current;
boolean isFirst = true;
while(aux != null)
{
if(!isFirst)
{
sb.append(", ");
}
isFirst = false;
sb.append(aux.data.toString());
aux=aux.next;
}
return sb.append("]").toString();
}
}
I'm getting a NullPointerException from the next() method in the Itr class on the line
nextUp = nextUp.getNext();
Am I doing something wrong in the CircularLinkedList class for it to not actually be circular or is there a problem with my driver/Itr classes? I'm kind of lost at this point. Any help is appreciated.
Create a custom class which implements Iterator and return the custom Iterator from your CLL.iterator method.
See LinkedList#ListItr for inspiration - but only conside the Iterator methods (next, hasNext, remove) for this exercise. A true circular linked-list will simply follow the next node, always, and has no end - hasNext will always return true if there is at least one element. If your CLL implementation has an "end", then make sure to "move back to the start" when it is encountered.
In addition, the CLL class should conform to Iterable, which means it has an iterator method to obtain an Iterator.

Java Hash Symbol Table Implementation

I built a symbol table using an array list filled with an object "pairs" that are singly-linked chains and hold a word and the number of times it occurs in a text file. I need to use this for the FrequencyCounter program that counts the number of words in a file. For some reason, I'm getting this error when running the the FrequencyCounter with the HashST:
Processed 1215985 words (19 sec; 19710 msec
Exception in thread "main" java.lang.NullPointerException
at HashST.hashIndex(HashST.java:60)
at HashST.get(HashST.java:105)
at FrequencyCounter.main(FrequencyCounter.java:112)
I have an idea that there's something wrong with my HashST and its not putting the pairs in the ArrayList like I wanted it to. Any suggestions on what is wrong with the implementation would be greatly appreciated.
Here is my code and the code for the FrequencyCounter:
import java.util.LinkedList;
import java.util.ArrayList;
import java.util.Iterator;
public class HashST<Key extends Comparable<Key>, Value> implements Iterable<Key> {
private ArrayList<Pair> chains;
private int numKeys;
private int numChains;
public class Pair
{
Key key;
Value value;
Pair(Key k, Value v)
{
key = k;
value = v;
}
Pair()
{}
Pair next;
}
/**
* Initialize an empty HashSt with a default of 64 empty chains.
*/
public HashST()
{
this(64);
}
/**
* Initialize an empty HashST with numChains emptychains.
* 387911 is a prime number about twice the number of distinct
* words in the leipzig1M.txt file.
*/
public HashST(int numChains)
{
this.numChains = numChains;
chains = new ArrayList<Pair>();
for(int i = 0; i < numChains; i++)
{
Pair p = new Pair(null, null);
chains.add(p);
}
}
/**
* compute the hash index for a key k if the number of
* chains is N
*/
private int hashIndex(Key k, int N)
{
return (k.hashCode() & 0x7fffffff) % N;
}
/**
* insert the Pair (k,v) into the appropriate chain and increment
* the number of keys counter or
* update the value for k if k is already in the hash table.
*
*/
public void put(Key k, Value v) {
int i = hashIndex(k, numChains);
Pair tmp = chains.get(i);
if(contains(k))
{
while(tmp.next != null)
{
if(tmp.key == k)
{
tmp.value = v;
return;
}
tmp = tmp.next;
}
}
else
{
Pair p = new Pair(k, v);
tmp.next = p;
numKeys ++;
}
}
/**
* return the value for key k if it is in the hash table
* or else return null if it is not.
*/
public Value get(Key k) {
int i = hashIndex(k, numChains);
Pair tmp = chains.get(i);
while(tmp.next != null)
{
if(tmp.key == k)
{
return tmp.value;
}
tmp = tmp.next;
}
return null;
}
/**
* remove the pair with key k if it is in the hash table
* otherwise no change.
*/
public void delete(Key k) {
if(contains(k))
{
return;
}
}
/**
* return true if the hash table contains a pair with key
* equal to k else return false
*/
public boolean contains(Key k) {
return (get(k) != null) ? true : false;
}
/**
* return the number of keys in the hash table
*/
public int size() {
return numKeys;
}
/**
* return a LinkedList<Key> containing the keys in the
* hash table
*/
public Iterable<Key> keys() {
LinkedList<Key> l = new LinkedList<Key>();
for(Pair p : chains)
{
while(p.next != null)
{
l.add(p.key);
p = p.next;
}
}
return l;
}
/**
* return an Iterator<Key> for the keys in the hash table
*/
public Iterator<Key> iterator() {
return keys().iterator();
}
}
And here is the Frequency Counter: http://algs4.cs.princeton.edu/31elementary/FrequencyCounter.java.html
According to your stack trace this would seem to be the line that threw a null pointer:
return (k.hashCode() & 0x7fffffff) % N;
So we have one object reference k, an integer constant, and a primitive N. Neither the constant nor the primitive can be null, the only thing being dereferenced here is k. So it looks like someone tried to get a value for a null k!

First year prgorammer needs help with a nullpointer exception in java

As a portion of a first year assignment, I need to create a class which uses a provided linked list implementation to implement a provided stack interface which is then tested by another provided class. I was able to easily complete the assignment using my own LL; however, I was told that I needed to use the one provided.
Exception in thread "main" java.lang.NullPointerException
at StackLL.<init>(StackLL.java:21)
at StackTester.main(StackTester.java:91)
Now I get null pointer exceptions whenever I try and run it. I thought this was being caused by the tester trying to grab the size of the list before the LL is initialized, but that doesn't seem to be the case and I am stumped.
Any tips on what I can do to fix the bug so that I can hand in the rest of the assignment? Thanks :)
The provided linked list implementation
LinkedList.java
/**
* LinkedList - a simple linked list of ints
*/
public class LinkedList
{
Node head;
int count;
public LinkedList ()
{
head = null;
count = 0;
}
/**
* Adds the given item to the start of the list
*/
public void addToStart (int item)
{
Node newNode = new Node();
newNode.value = item;
if (head != null)
newNode.next = head;
head = newNode;
count++;
}
/**
* Adds the given item to the end of the list
*/
public void addToEnd (int item)
{
if (size() == 0)
{
addToStart (item);
}
else
{
Node n = head;
while (n.next != null)
n = n.next;
n.next = new Node(item);
count++;
}
}
/**
* Remove and return the first item in the list
*/
public int removeFromStart ()
{
if (size() == 0)
throw new EmptyListException();
int valtoReturn = head.value;
head = head.next;
count--;
return valtoReturn;
}
/**
* Remove and return the last item in the list
*/
public int removeFromEnd ()
{
if (size() == 0)
throw new EmptyListException();
if (size() == 1)
return removeFromStart();
else
{
Node n = head;
while (n.next.next != null)
n = n.next;
int valtoReturn = n.next.value;
n.next = null;
count--;
return valtoReturn;
}
}
/**
* Return the number of items contained in this list
*/
public int size ()
{
return count;
}
/**
* A basic node class
*/
private class Node
{
int value;
Node next;
Node()
{
}
Node (int value)
{
this.value = value;
}
}
// random testing code for the Linked List
public static void main (String [] args)
{
LinkedList l = new LinkedList();
l.addToStart (5);
int val = l.removeFromStart();
System.out.println (val == 5 ? "passed" : "failed");
System.out.println (l.size() == 0 ? "passed" : "failed");
for (int x = 0; x < 10; x++)
l.addToEnd (x);
System.out.println (l.size() == 10 ? "passed" : "failed");
while (l.size() > 0)
System.out.print (l.removeFromEnd() + " ");
System.out.println ();
}
}
/**
* The exception class when a removal action is performed on
* an empty list.
*/
class EmptyListException extends RuntimeException
{
public EmptyListException ()
{
super();
}
public EmptyListException (String s)
{
super(s);
}
}
My implementation
StackLL.java
/**
* A linked list implementation of the Stack ADT.
*
*/
public class StackLL implements Stack
{
// The linked list that will contain the values in the stack
private LinkedList values;
public int size()
{
return values.size();
}
public boolean isEmpty()
{
if (values.size() <= 0) {
return true;
}
return false;
}
public void push(int element)
{
values.addToStart(element);
}
public int pop() throws StackEmptyException
{
if (values.size() == 0) {
throw new StackEmptyException();
}
else {
return values.removeFromStart();
}
}
public int peek() throws StackEmptyException
{
if (values.size() == 0) {
throw new StackEmptyException();
}
else { //This is a pretty silly way to do this, but I can't think of any other way without making my own linked list method.
int elementVal = values.removeFromStart();
values.addToStart(elementVal);
return elementVal;
}
}
}
The Provided Interface
Stack.java
/**
* Stack.java
*
* A specification of the Stack ADT
*
*/
public interface Stack
{
int size();
boolean isEmpty();
void push (int element);
int pop() throws StackEmptyException;
int peek() throws StackEmptyException;
}
class StackEmptyException extends Exception
{
public StackEmptyException ()
{
super();
}
public StackEmptyException (String s)
{
super(s);
}
}
The Tester
StackTester.java
/**
* StackTester.java
*
* Some test cases for a stack.
*/
public class StackTester
{
public static void testOne (Stack s)
{
try
{
if (s.size() != 0 || !s.isEmpty())
System.out.println("1: Failed size or isEmpty.");
s.push(1);
s.push(2);
if (s.size() != 2 || s.isEmpty())
System.out.println("2: Failed size or isEmpty.");
if (!(s.pop() == 2))
System.out.println("3: Failed pop");
if (!(s.peek() == 1))
System.out.println("4: Failed peek");
if (!(s.pop() == 1))
System.out.println("5: Failed pop");
if (s.size() != 0 || !s.isEmpty() )
System.out.println("6: Failed size or isEmpty.");
}
catch (StackEmptyException e)
{
System.out.println(e);
}
}
public static void testTwo (Stack s)
{
try
{
for (int i = 0; i < 100; i++)
{
s.push(i);
}
if (s.size() != 100)
System.out.println("7: Failed size.");
for (int i = 99; i >= 0; i--)
{
if (!(s.pop() == i))
{
System.out.println("Failed pop for: " + i);
break;
}
}
}
catch (StackEmptyException e)
{
System.out.println("Failed testTwo.");
System.out.println(e);
}
}
public static void testThree (Stack s)
{
try {
while (!s.isEmpty())
s.pop();
}
catch (StackEmptyException e) {
System.out.println ("Failed empty stack test (popped on a non empty stack threw exception)");
}
try
{
s.pop();
System.out.println("Failed empty stack test.");
}
catch (StackEmptyException e)
{
/* If we get here, we
* passed the previous test.
*/
}
}
public static void main (String args[])
{
Stack s1 = new StackLL();
Stack s2 = new StackLL();
Stack s3 = new StackLL();
testOne(s1);
testTwo(s2);
testThree(s3);
}
}
You have private LinkedList values; in StackLL.
That says "this class has a field called values of type LinkedList". It does not assign an object to values, so when you try to access it, a NullPointerException occurs.
You should be able to fix it by assigning a value to values, i.e.:
private LinkedList values = new LinkedList();
(I don't know if you've learned about generics yet, but if you have, remember to add the type, e.g. LinkedList<Person>.)
Look at the line of code given in the error message (I'm assuming its the return statement in your size() function) and think about the meaning of NullPointerException -- the variable which is null is not yet initialized. Then ask yourself, do I expect this variable to be initialized here? If yes, then ask why isn't it and where should it be initialized? If no, then you have a logic error at the given location.
You aren't ever instantiating a LinkedList object in StackLL. So the first time you try to access it, it blows a NPE.

Categories