【问题标题】:Generic array In JavaJava中的通用数组
【发布时间】:2016-02-01 12:39:48
【问题描述】:

我想弄清楚为什么我的代码会出错 -

线程“main”java.lang.Error 中的异常:未解决的编译问题:

The method maximum(T[]) in the type find_max is not applicable for the arguments (int[])
The method maximum(T[]) in the type find_max is not applicable for the arguments (double[])

代码

public static <T extends Comparable<T>> T maximum(T [] a) throws Exception { 
    System.out.println("here"); 
    T max=a[0]; // assume x is initially the largest 
    for (T i : a) { 
        if (i.compareTo(max) > 0) { 
            max=i; 
        } 
    } 
    return max; // System.out.println("Max is " + max); 
}

【问题讨论】:

  • public static > T maximum(T [] a) throws Exception { T max=a[0]; // 假设 x 最初是最大的 for (T i : a) { if (i.compareTo(max) > 0) { max=i; } } 返回最大值; }
  • 能否提供代码sn-p和错误堆栈?
  • 因为intdouble 是原始类型,不能用于泛型。
  • 忘记放在那里了:P

标签: java arrays generics


【解决方案1】:

对于像这样的方法签名:

public static <T extends Comparable<T>> T maximum(T [] a)

T 类型参数代表 引用类型(甚至更多 - 引用类型 TComparable&lt;T&gt; 的子类型),后来它被替换为一些特定的引用类型。

您正在使用int[]double[] 调用该方法。在这些情况下,T 的可能替代品是 intdouble,它们不是引用类型,而是原始类型。

如果你这样做了(例如):

Integer array = new Integer[] { 1, 2, 3 };
method(array);

那么编译器错误就不会出现,因为Integer(不像int)是一个引用类型并且是Comparable&lt;Integer&gt;的子类型,这使它成为一个合适的替代品T 在运行时。

【讨论】:

  • 谢谢...帮助很大:)
猜你喜欢
  • 1970-01-01
  • 2016-09-19
  • 2020-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-28
相关资源
最近更新 更多