Search code examples
javagenericsinterfacecomparable

Generic type implementation of linked list and swapping two generic objects


Generic class implementing Comparable

My first question is how to correctly implement a Generic class that implements compareTo. My current class definition is:

public static class Node<T> implements Comparable<Node<T>>{

and my compareTo method is:

public <T extends Comparable<T>> int compareTo(Node<T> n){

1a. Are these definitions correct?

1b. How should I complete my compareTo method? Much of the literature I have found online has referenced using .compareTo() within the method itself, which does not make sense to me.

Swap two nodes in linked list:

My current method definition is

public void swap(Node<T> n1, Node<T> n2){
    // swap
}
  1. Is it possible to swap two nodes in a singly linked list implementation, or does the swap method inherently require a doubly linked implementation of a linked list?

Solution

  • 1a. Are these definitions correct?

    Not completely. The definition you have for compareTo is declaring a type variable and this is probably wrong:

    public <T extends Comparable<T>> int compareTo(Node<T> n){
    

    (It actually shouldn't compile.)

    It should just be:

    @Override
    public int compareTo(Node<T> n){
    

    1b. How should I complete my compareTo method?

    That depends on what you're supposed to be comparing. Since you haven't specified, we don't know. ; )

    Much of the literature I have found online has referenced using .compareTo() within the method itself, which does not make sense to me.

    Here's an example of how this would typically be used:

    // saying T must also be Comparable:
    // it's possible you are supposed to do
    // this for your own Node declaration too
    //         vvvvvvvvvvvvvvvvvvvvvvv
    class Node<T extends Comparable<T>> implements Comparable<Node<T>> {
        T data;
    
        @Override
        public int compareTo(Node<T> that) {
            return this.data.compareTo( that.data );
        }
    }
    

    Now we can compare nodes, but it actually delegates to whatever the data is. We don't know or care what the data is (though it can't be null), just that it implements Comparable.

    2. Is it possible to swap two nodes in a singly linked list implementation, or does the swap method inherently require a doubly linked implementation of a linked list?

    The hint here is that you don't need to swap nodes, just whatever their data is.