我正在阅读 Oracle 泛型教程,但在使用以下代码时遇到问题:
import java.util.*;
public class GenericReturn {
public static void main(String[] args){
Integer index = 1;
ArrayList<Integer> AL = new ArrayList<>();
AL.add(10);
AL.add(20);
AL.add(30);
Number s = choose(index, AL);
System.out.println(s);
}
static <T, U, S> S choose(T a1, U a2) { return a2.get(a1); }
}
它不会编译错误是:
javac GenericReturn.java
GenericReturn.java:12: error: cannot find symbol
static <T, U> T choose(T a1, U a2) { return a2.get(a1); }
^
symbol: method get(T)
location: variable a2 of type U
where T,U are type-variables:
T extends Object declared in method <T,U>choose(T,U)
U extends Object declared in method <T,U>choose(T,U)
1 error
有人可以帮我吗?
几乎肯定有人想将其标记为重复项,但请不要 - 泛型已经足够难了,而无需深入研究另一个类似的问题,而该问题并不能完全涵盖您需要了解的内容!
最佳答案
更改:
static <T, U, S> S choose(T a1, U a2) { return a2.get(a1); }
致:
static <U extends List<S>, S> S choose(Integer a1, U a2) { return a2.get(a1); }
或者更简化的版本:
static <S> S choose(Integer a1, List<S> a2) { return a2.get(a1); }
话虽如此,Java 中的所有 Collection
类都已经通用,因此无需首先编写这样的包装方法。
关于java - 通用返回类型 - 无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31356751/