泛型:类型不适用于参数

rsh*_*hah 0 java generics algorithm

使用泛型,编译器应该在运行时推断对象T的类型,但是它给了我一个静态违规,如标题中所述,我无法弄清楚(使用其他问题)来解决这个问题.

这是我的方法:

public static <T> boolean linearSearchIterative(T[] array, T obj) {
    for(int i = 0; i < array.length; i++) {
        if(array[i].equals(obj)) {
            return true;
        }
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

以下是我在main方法中声明的方法:

int x[] = {2, 3, 5, 6, 1};
int y = 1;
System.out.println(LinearSearch.linearSearchIterative(x, y));
Run Code Online (Sandbox Code Playgroud)

Cra*_*ing 5

Java中的泛型仅适用于引用类型,而不适用于基本类型.

将运行代码更改为:

Byte x[] = {2, 3, 5, 6, 1}; // or Integer
Byte y   = 1;               // or Integer
Run Code Online (Sandbox Code Playgroud)

  • 因为Java 5功能称为autoboxing. (2认同)