[问题] Generic 的 cast 问题

楼主: changyuheng (张昱珩)   2014-12-12 00:08:17
希望下面的 mList 可以不 cast 直接使用,请问是不是做不到?
import java.util.LinkedList;
import java.util.List;
public class AbsList {
private List<?> mList;
private String mType;
public AbsList newInstance(String type) {
mType = type;
switch (type) {
case "String":
mList = new LinkedList<String>();
break;
case "Number":
mList = new LinkedList<Number>();
}
return this;
}
public void go() {
switch (mType) {
case "String":
((List<String>) mList).add("A");
for (String s : (List<String>) mList)
System.out.println(s);
break;
case "Number":
((List<Number>) mList).add(0);
for (Number n : (List<Number>) mList)
System.out.println("" + n);
}
}
public static void main (String[] args) {
new AbsList().newInstance("String").go();
}
}
作者: swpoker (swpoker)   2014-12-12 10:14:00
本身的逻辑就怪怪的
作者: ssccg (23)   2014-12-12 10:45:00
要不cast你type就要用generic,那你整个class就要有个Typeparameter,你现在的作法完全不generic,跟用List没差别..

Links booklink

Contact Us: admin [ a t ] ucptt.com