通用方法 - “private <T> boolean (T[], T[])”

zje*_*zje 5 java arrays generics

我对 Java 中的泛型真的很陌生。我正在尝试创建一个简单的方法来比较两个相同类型的数组,但我想使用通用方法。我在下面附上了一个 MWE:

public class MWE {
  public static void main(String[] args){
    int[] test1,test2;
    test1 = new int[2];
    test2 = new int[2];
    checkArray(test1,test2);
  }

  private <T> boolean checkArray(T[] check, T[] test) {
    if(check.length != test.length)
      return false;

    for(int i=0;i<check.length;i++)
      if(check[i]!=test[i])
        return false;

    return true;
  }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试编译时,我得到:

MWE.java:6: <T>checkArray(T[],T[]) in MWE cannot be applied to (int[],int[])
    checkArray(test1,test2);
    ^
1 error
Run Code Online (Sandbox Code Playgroud)

Hur*_*rda 5

泛型仅适用于对象,您必须为原始数组提供重载方法。(其中可以切换到Integer[]、Boolean[]等)


zos*_*tay 4

尝试使用 Integer[] 而不是 int[]。

更详细地说:

Java 泛型始终与类一起使用,因此在使用此类泛型时,您需要使用每种类型的类版本。由于 Java 通过自动装箱自动将 int 值转换为 Integer 对象值,因此除了所使用的类型名称之外,代码中实际上不应该有任何差异。