Java中的静态和非静态vs泛型和通配符

bra*_*orm 1 java generics static wildcard

考虑以下示例

class test<E>{
    public int getNum(int i){
        return i;
    }

    public E getNum1(E i){
        return i;
    }

    public static <E> E getNum(E i){
        return i;
    }
    }
Run Code Online (Sandbox Code Playgroud)

第一种方法声明:返回类型是已知的

第二种方法声明:返回类型是一些未知的

第三种方法声明:返回类型是一些未知的+静态

问题:当静态方法用于泛型时,<E>必须指定类型参数.它为什么会这样?或者类型参数究竟是什么意思,它的目的是什么?当方法是非静态的时我们没有类型参数,虽然在这种情况下我们<E>在类声明中有如public class <E> {...}

在外卡上考虑这一点

//This does not compile, how to make it correct
    public static  getIndex(List<?>, int index){
        return list.get(index);
    }

    public static <E> E getIndex1(List<E> list, int index){
        return list.get(index);
    }
Run Code Online (Sandbox Code Playgroud)

同样,第一种方法不能编译.我不知道如何使用无界通配符为返回类型进行编译

上面两个方法声明有什么区别?

通配符?表示任何类型,E表示某种未知类型.

any type是怎么回事some unknown type

Sot*_*lis 5

问题:当静态方法用于泛型时,必须指定类型参数.它为什么会这样?或者类型参数究竟是什么意思,它的目的是什么?当方法是非静态的时,我们没有类型参数,尽管在这种情况下我们在类声明中有公共类{...}

一个static方法不属于一个实例,它属于一类.类没有泛型类型(实例可以).

所以没有意义

class test<E>{
    public static E getNum(E i){
        return i;
    }
}
Run Code Online (Sandbox Code Playgroud)

你会得到的Cannot make a static reference to the non-static type E.

类声明中的type参数适用于实例

test<String> anInstance = new test<String>();
Run Code Online (Sandbox Code Playgroud)

这个

//This does not compile, how to make it correct
public static  getIndex(List<?>, int index){
    return list.get(index);
}
Run Code Online (Sandbox Code Playgroud)

因为您没有提供返回类型,并且List<?>参数没有变量声明.


any type是怎么回事some unknown type

当您执行泛型类型声明时

public class Test<E> {}
Run Code Online (Sandbox Code Playgroud)

E不是一个未知的类型.它是在创建实例时选择的定义良好的类型.

Test<String> test = new Test<>();
Run Code Online (Sandbox Code Playgroud)

EString.

引用Louis Wasserman的话

E表示您可以命名并稍后引用的某种未知类型.?表示某些未命名的未知类型,以后不能引用.


通过阅读关于泛型官方Java教程,您将获得很多收获.