2015-07-11 82 views
0

我读了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 

任何人都可以帮我一下吗?

有人几乎肯定要将此标记为重复项,但请不要 - 泛型非常困难,如果不翻阅另一个类似的问题,它不能涵盖您需要知道的内容!

+1

'static ,S> S choose(Integer a1,U a2){return a2.get(a1); }' – CKing

+0

这就是答案 - 谢谢! – user1501247

+0

现在,我必须找出它为什么起作用,而我的原创没有! – user1501247

回答

2

变化:

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); } 

话虽这么说,所有Collection Java中的类都已经通用所以没有必要写这样一个包装方法od首先。