【问题标题】:Why would a method that accepts an interface reject an implementation of that interface?为什么接受接口的方法会拒绝该接口的实现?
【发布时间】:2016-01-24 22:44:36
【问题描述】:

我正在尝试找出教科书中问题的答案,但遇到了麻烦。问题是要求我检查一个输入数组以查看它是否包含适合某些功能的对象。除了我尝试使用作为实现接口的类之一的输入来实现该方法之外,此功能的每个功能似乎都运行良好。

例子:

main(){
  boolean r1 = has(input, checkFor2);
}

public static <T> boolean has(T[] input, Check<T> c){
  // does its check algorithm and returns a boolean
}

static public interface Check<T>{
  boolean isContained(T item);
}

static public class checkFor2 implements Check<Integer>{
  public boolean isContained(Integer val){
    // does a check algorithm
  }
}

// Other check algorithms implementing Check<T> follow as well.

我得到的错误是在 main 方法中调用“has”。它说:

main类型中的方法has(T[], main.Check&lt;T&gt;)不适用于参数(int[], main.checkFor2)

它的建议是将方法中的类更改为特定的类而不是接口,这违背了以这种方式编写它的目的。

我在编写这个代码时犯了一些新手错误吗?

【问题讨论】:

    标签: java generics interface


    【解决方案1】:

    问题实际上与您的界面无关。这与您提供原始 int 数组 int[] 而不是 Integer[] 数组这一事实有关。

    在方法中

    public static <T> boolean has(T[] input, Check<T> c){
    

    T 的类型是从您提供的参数中推断出来的。在这种情况下,您将提供int[]Check&lt;Integer&gt;。但是,an int[] cannot be boxed to an Integer[],所以类型推断失败:T 无法推断为Integer

    因此,解决方案是将原始数组更改为 Integer[] 数组,并将其作为第一个参数发送给您的方法。

    【讨论】:

    • 道德:不要妄下结论。
    猜你喜欢
    • 2019-08-19
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 2014-09-16
    • 1970-01-01
    • 1970-01-01
    • 2019-01-08
    • 2017-12-17
    相关资源
    最近更新 更多