Reputation: 117675
So recently I have been working on "phonebook" project that uses "Binary Search Tree".
The Phonebook is using BSTree. Each node of the tree is BTNode. In the main class, I replace E with Pair class, which has (String name, String number), when I define the nodes.
I have the following comparator class to compare between 2 E types:
import java.util.Comparator;
public class BTNodeComparator<E extends Comparable<E>> implements Comparator<E>
{
public int compare(final E a, final E b)
{
return (a.compareTo(b));
}
}
and I use it in BSTree.
Also, I define compareTo() method in Pair class:
@Override
public int compareTo(Pair pair)
{
return name.compareTo(pair.getName());
}
Now, when I run the program and it comes to the comparator, it gives me errors at the comparator because now it compares between two Pairs
How can I solve this issue? What I want is to compare between the names of the two pairs ?
This error what I got after inserting the second node (Pair) in BST:
java.lang.NullPointerException
at Pair.compareTo(Pair.java:36) // @ return name.compareTo(pair.getName());
at Pair.compareTo(Pair.java:2) // @ public class Pair implements Comparable<Pair>
at BTNodeComparator.compare(BTNodeComparator.java:24) // @ return (a.compareTo(b));
at BTNodeComparator.compare(BTNodeComparator.java:20) // @ public class BTNodeComparator<E extends Comparable<E>> implements Comparator<E>
at BSTree.search(BSTree.java:285)
at BSTree.insert(BSTree.java:300)
at PhoneBook.main(PhoneBook.java:25)
BTW, I decleared BTNodeComparator in BSTree as follows:
protected Comparator<E> c = new BTNodeComparator();
if (c.compare(target, cursor.getElement()) < 0) cursor = cursor.getLeft();
Thanks in advance for any help :)
Upvotes: 0
Views: 156
Reputation: 10959
Your stacktrace indicates that your problem is that name is null in a Pair.
.. or pair that is an argument to compareTo
Upvotes: 3