Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Comparator with List of Objects in Java

I'd like to sort my objects of Type AVLNode by their key (type String). I instantiated a Comparator and want to apply the compareTo Method on the String attribute. But, my IDE shows me the error Cannot resolve method compareTo. I don't understand why I cant use the compareTo method on a string an this point.

import java.util.*;

public class AVLTreeTest {
    public static void main(String[] args){

        Comparator<AVLNode>myComp2 = new Comparator<AVLNode>() {
            @Override public int compare(AVLNode n1, AVLNode n2) {
                return n1.getKey().compareTo(n2.getKey());
            }
        };

        AVLNode<String, AVLNode> a1 = new AVLNode( "test3", new Cuboid (2,3,4,5,6,7) );
        AVLNode<String, AVLNode> a2 = new AVLNode( "test2", new Cuboid (2,3,4,5,6,7) );
        AVLNode<String, AVLNode> a3 = new AVLNode( "test8", new Cuboid (2,3,4,5,6,7) );
        AVLNode<String, AVLNode> a4 = new AVLNode( "test1", new Cuboid (2,3,4,5,6,7) );

        List<AVLNode> listOfNodes = new ArrayList<AVLNode>();
        listOfNodes.add(a1);
        listOfNodes.add(a2);
        listOfNodes.add(a3);
        listOfNodes.add(a4);
        Collections.sort(listOfNodes, myComp2);

        for (AVLNode node : listOfNodes){
            System.out.println(node);
        }
    }
}

This is my AVLNode Class

public class AVLNode<K, V>  {

    private AVLNode<K, V> left, right, parent;
    private int height = 1;
    private K key;
    private V value;

    public AVLNode() {}
    public AVLNode(K key, V value) {
        this.key = key;
        this.value = value;
    }


    public V getValue() {
        return value;
    }

    public K getKey() {
        return key;
    }
}

What am I doing wrong?

like image 801
zinyosrim Avatar asked Dec 11 '22 06:12

zinyosrim


1 Answers

AVLNode is generic, parameterized with K and V. In your Comparator<AVLNode>, AVLNode is raw. That is, K and V are unknown. This means the compiler actually does not know if K is Comparable.

Try making it Comparator<AVLNode<String, ?>>.

Unrelated, but also use new AVLNode<>(...).

like image 150
lexicore Avatar answered Dec 23 '22 08:12

lexicore