My project is a Phonebook that is using BSTree<E>
. Each node of the tree is BTNode<E>
. 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> implements Comparator<E>
{
public int compare(E a, E b) throws ClassCastException
{
return ((Comparable<E>) a).compareTo(b);
}
}
and I use it in BSTree<E>
.
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 ?
Sorry for my bad explanation. My English is weak.
=========================
Edit:
@Tim: After trying your solution it gives me this error:
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();