静态泛型方法的返回类型可以取决于其参数吗?

cub*_*uce 0 java generics

我“只是”想编写一个静态泛型方法,该方法将Collection<E>任何类型的泛型E作为其输入,并输出适当类型的结果Vector<E>。由于类型E在编译时始终已知,因此这不应该是问题 - 但它是......因此,稍后的调用应如下所示:

Collection<String> coll = ...
Vector<String> vec = Convert.toVector(coll); // either this or...
Vector<String> vec = Convert<String>.toVector(coll);
Run Code Online (Sandbox Code Playgroud)

这是我尝试过的 - 都没有成功:

import java.util.Collection;
import java.util.Vector;

public class Convert<E> {

    // 1st try, same type E as class => Error: Cannot make a static reference to the non-static type E
    public static Vector<E> toVector1(Collection<E> coll) {
        return new Vector<E>();
    }

    // 2nd try, a new type X. => Error: X cannot be resolved to a type
    public static Vector<X> toVector2(Collection<X> coll) {
        return new Vector<X>();
    }

    // 3rd try, using wildcard. => Error: Cannot instantiate the type Vector<?> 
    public static Vector<?> toVector3(Collection<?> coll) {
        return new Vector<?>();
    }

    // 4th try, using bounded wildcard. => Error: Cannot make a static reference to the non-static type E
    public static Vector<? extends E> toVector4(Collection<? extends E> coll) {
        return new Vector<E>();
    }
}
Run Code Online (Sandbox Code Playgroud)

难道这根本不可能吗?如果没有,是否有充分的理由不这样做?或者我只是做错了?也许有一些使用 Lambda 表达式的解决方案?

Era*_*ran 5

您应该为静态方法提供自己的泛型类型参数:

public static <T> Vector<T> toVector1(Collection<T> coll) {
    return new Vector<T>();
}
Run Code Online (Sandbox Code Playgroud)

<T>您在方法的返回类型之前缺少泛型类型参数声明 ( )。