1

这是我当前的代码:

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

4

1 回答 1

-2

One solution could be something like :

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);
    }

}

After, you can call it with SingletonAList.getInstance(String.class);

于 2013-10-28T14:42:19.147 回答