简体   繁体   中英

Implementing Comparable for a Node in Java

I'm new to Java, thus the questions might look trivial to some. I've an implementation of a Node class, that uses a generic data type T. I want to implement a comparable to compare two instances of T.

This is my code.

private class Node<T> implements Comparable<T> {
        private T data;
        private Node next;

        public Node(T data){
            this.data = data;
            this.next = null;
        }

        @Override
        public int compareTo(T other) {
            if(this.data == other) return 0;
            if(this.data < other) return 1;
            if(this.data > other) return -1;
        }
    }

This code doesn't compile as Java throws bad operand type error. What is the correct way to write the compareTo function. Any help appreciated.

First, you need the T s to be comparable between themselves. What you want is basically just

private class Node<T extends Comparable<T>> implements Comparable<Node<T>> {
    ...

    @Override
    public int compareTo(Node<T> other) {
       return data.compareTo(other.data);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM