有如下类:
package com.sily;import java.util.ArrayList;
import java.util.List;public class GenericSily {
    public List<?> l(int i) {
        switch (i) {
        case 1:
            return new ArrayList<Double>();
        default:
            return new ArrayList<String>();
        }
    }    public List<Double> getDoubleList() {
        return (List<Double>)l(1);//此处会有警告
    }    public static void main(String[] args) {
        // TODO Auto-generated method stub
    }
}以上类很简单,方法public List<?> l(int i)是一个根据参数返回不同类型的List,而方法public List<Double> getDoubleList() 是返回Double类型的List,但在此方法中如果按如上的代码所示就会警告,请问该如何处理这个方法?

解决方案 »

  1.   

    这也只是一个变相的解决办法,没有从根本上解决问题,既然jdk1.5不支持此类方式,就应该有规范的方法可以解决这个问题,那到底什么是解决此类问题的规范方法呢?
      

  2.   

    public List<? extends Object> get(int i) {
      

  3.   

    it seems impossible to explicitly type cast from List<?> to List<Double> even you know l(1) will return a List<Double>. However complier won't know l(1) will return List<Double> in compling time so it will give you the warning.If you insist on the getDoubleList method be there, you can change it to
    public List<?> getDoubleList() {
      return l(1);
    }then you should make sure l() is only called with argument as 1 which can guarantee the List<Double> is return type. But obviously it's not a good way to define method.