有如下类:
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,但在此方法中如果按如上的代码所示就会警告,请问该如何处理这个方法?
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,但在此方法中如果按如上的代码所示就会警告,请问该如何处理这个方法?
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.