Question

I have got some problems of java type parameter. Here is the code. I have a class ListNode, and a class MyComparator implementing Comparator interface.

class ListNode {
    int val;
    ListNode next;
}

class MyComparator<ListNode> implements Comparator<ListNode> {
    @Override
    public int compare(ListNode n1, ListNode n2) {
        if (n1.val < n2.val)
            return -1;
        else if(n1.val == n2.val)
            return 0;
        else
            return 1;
    }
}

However the compiler reports that "the type parameter ListNode is hiding the type ListNode" at the declaration line of MyComparator, and it leads to "val can not be resolved" error in the overriding implementation of compare(). I am quite confused about the type parameter here, could anyone give me some tips please?

Était-ce utile?

La solution

Use

class MyComparator implements Comparator<ListNode> {

instead of

class MyComparator<ListNode> implements Comparator<ListNode> {
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top