这是我目前的代码:
import java.util.ArrayList;
public class SingletonAList<T> {
private final ArrayList<T> aL = new ArrayList<T>();
SingletonAList() {}
public ArrayList<T> getList(T t) {
return aL;
}
}
我要做的是让它返回类型的单例列表(如果存在);如果不是为了创建一个新的T型;
例如,进行了三次getList调用;
getList(Obj1);
getList(Obj2);
getList(Obj1);
On first getList a new ArrayList<Obj1> would be created;
on second getList a new ArrayList<Obj2> would be created;
and on third getList the same arrayList from the first call would be returned.
任何实施建议?我一直在搞乱......似乎新的调用必须在getList调用中;可能还有另一个已经实例化的类型列表?
答案 0 :(得分:-2)
一种解决方案可能是:
public class SingletonAList {
private static Map<Class, List> lists = new HashMap<Class, List>();
public static <T> List<T> getInstance(Class<T> klass) {
if (!lists.containsKey(klass)) {
lists.put(klass, new ArrayList<T>());
}
return lists.get(klass);
}
}
之后,您可以使用SingletonAList.getInstance(String.class);