Results 1 to 1 of 1
  1. #1
    FOUAD-SPIDER is offline Member
    Join Date
    Feb 2011
    Posts
    4
    Rep Power
    0

    Smile 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:

    Java Code:
    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<E>.

    Also, I define compareTo() method in Pair class:


    Java Code:
    @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 ?

    Sorry for my bad explanation. My English is weak.

    ===================

    This error what I got after insert the second node (Pair) in BST:


    Java Code:
    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:
    Java Code:
    protected Comparator<E> c = new BTNodeComparator();
    if (c.compare(target, cursor.getElement()) < 0) cursor = cursor.getLeft();
    Also, I attached the .java files

    Thanks in advance for any help :)
    Attached Files Attached Files

Similar Threads

  1. comparing Graphs and Comparing Matrix
    By jetnor in forum New To Java
    Replies: 0
    Last Post: 03-27-2011, 02:40 AM
  2. Homework help involving comparing Color objects to Strings
    By SergeantJoKer in forum New To Java
    Replies: 12
    Last Post: 09-25-2010, 07:13 AM
  3. Help with comparing generic types
    By repairmanjack in forum New To Java
    Replies: 4
    Last Post: 09-22-2009, 07:41 AM
  4. Replies: 1
    Last Post: 01-22-2009, 05:25 PM
  5. Replies: 0
    Last Post: 12-22-2008, 07:16 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •