Search code examples
javalistcomparablecompareto

Java: How to use the compareTo method to check the order of 2 nodes


I am working on a programming assignment and I could use some help understanding the compareTo method.

One of the questions of the assignment is to add an incoming element to a list. If the list is sorted, I am supposed to put the new node in its correct position. The list can be either sorted in an ascending or descending order. I thought I could check which is the order by comparing the head node to the node after (node.getNext()) but I am not sure. The line of code that I am not sure on is the following:

if(head.getContent().compareTo(tp.getContent())==1)

head is the first node is a generic data type T, which has already been added. tp is head.getNext() just to save space and is also a generic data type T, since I am sure I will be typing it again. I did not write a compareTo method on the program because the professor told me that simply call the compareTo method to compare another generic data type. Also, I am not sure on the difference between:

extends Comparable<T>

and

implements Comparable<T>

but the assignment requires me to use the first one.

if the head node element is 1 and the next on is 3, what will the output of the if statement be? true or false?


Solution

  • Basically the way to think of compareTo is to ALWAYS put a zero on the other side of it and then imagine that the operator is between the two arguments.

    A.compareTo(B) == 0; // A == B
    A.compareTo(B) > 0; // A > B
    A.compareTo(B) >= 0; // A >= B
    
    //etc etc etc
    

    This makes it much easier to read and saves you trying to figure out what you actually meant by >-1 or something in two years