这是我当前的代码:

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调用中;可能还有另一个已经实例化的类型列表?

最佳答案

一种解决方案可能是这样的:

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);进行调用

10-08 18:40