Issues with comparing two generic objects
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.getLe开发者_开发问答ft();
The only possible failure I could see is ClassCastException
.
To fix your code you will need to specify your Pair
class like this:
class Pair implements Comparable<Pair> {
String name;
String number;
//some implementation stuff...
@Override
public int compareTo(Pair o) {
return name.compareTo(o.name);
}
}
In general, if your Comparator
implementation relies on the generic type implementing Comparable
then you should specify it like this:
public class BTNodeComparator<E extends Comparable<E>> implements Comparator<E> {
public int compare(final E a, final E b) {
return a.compareTo(b);
}
}
Doing so just gives you compile time safety without changing the semantics of how the Comparator
works.
Based on your comment, I'm guessing you are embedding your BTNodeComparator
into the BSTree
class as a nested inner-class, which means you probably can't make that change without changing the type definition in the BSTree
declaration.
精彩评论