1

This is my current code:

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

What I am looking to do is have it return a Singleton List of the type if it exists; if not to create a new one of type T;

so example three getList calls are made;

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.

Any implementation suggestions? I have been messing around...it seems that the new call must be in the getList call; and possibly another list of Types that have already been instantiated?

Dax Duisado
  • 197
  • 2
  • 11
  • 4
    Due to type erasure, you can't do that. (unless you use a `Map, ArrayList>>`) – SLaks Oct 28 '13 at 14:15
  • “On first … would be created; on second … would be created;” Do you know what the “single” in “singleton” stands for? – Holger Oct 28 '13 at 14:36
  • I have done similar thing before, my implementation used a Map, just like @SLaks suggested. – NickJ Oct 28 '13 at 14:37
  • @Holger: http://stackoverflow.com/q/686630/34397 – SLaks Oct 28 '13 at 14:37
  • @SLaks: so what? I don’t see the word “singleton” in this contribution. – Holger Oct 28 '13 at 14:39
  • @Holger: It's exactly what he's trying to do. It's a very useful pattern, whether you call it a singleton or not. (it is a singleton per-constructed-type) – SLaks Oct 28 '13 at 14:40
  • @SLaks: if the questioner was aware of the fact that it’s not a singleton what he wants he was able to solve the problem on his own, maybe. – Holger Oct 28 '13 at 14:44

1 Answers1

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

wishper
  • 615
  • 6
  • 18