[問題] 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