Unable to find a method belonging to an object

前端 未结 2 1527
旧巷少年郎
旧巷少年郎 2021-01-22 03:54

I believe I am making a really simple mistake/ overlooking something trivial.

import java.util.Comparator;

public class NaturalComparator {

            


        
相关标签:
2条回答
  • 2021-01-22 04:16

    You accidentally created a generic type parameter Integer which has nothing to do with the Integer class, and you didn't implement Comparator. Try

    public class NaturalComparator implements Comparator<Integer>
    

    Placing an identifier in <> on the class declaration declares a generic type parameter, but placing an identifier in <> on the implements/extends clause is a passing a type argument.

    0 讨论(0)
  • 2021-01-22 04:21

    You are shadowing the type java.lang.Integer with a type parameter variable you decided to name Integer.

    Your code is equivalent to

    public class NaturalComparator<T> {
    
        public int compare(T o1, T o2) {
            return o1.intValue() - o2.intValue();
        }
    }
    

    Which obviously doesn't compile since Object (the bound of T) doesn't declare a intValue() method.

    What you want is

    public class NaturalComparator implements Comparator<Integer> {
    
        @Override
        public int compare(Integer o1, Integer o2) {
            return o1.intValue() - o2.intValue();
        }
    }
    

    in which case java.lang.Integer is used as a type argument.

    0 讨论(0)
提交回复
热议问题