2

I want to create a Cache object. Naturally, I want this cache object to be typed. The problem is how do I create the empty array to insert the objects into (because I have no type reference).

public class Cache<T> {
    int size;

    T[] items;

    public Cache(int size){
        this.setSize(size);
    }

    public void setSize(int size){
        this.size = size;
        this.items = new T[size]; //this doesnt work!
    }

}
chacham15
  • 12,538
  • 21
  • 88
  • 185
  • 2
    Welcome to the wonderful world of generics. This can't be achieved using the method you are trying, usually, you need to provide a prototype or factory method to do it. Consider using an implementation of `List`, like `ArrayList` instead – MadProgrammer Sep 12 '14 at 03:40
  • Additionally, you need a Key type as well for a cache. Unless it's supposed to be a pool. **Please**, consider using an existing cache (or object pool). – Elliott Frisch Sep 12 '14 at 03:43
  • @MadProgrammer "Welcome to the wonderful world of generics." haha, I like that. I guess that I thought this *should* be possible because you can assign null to any object, and that doesnt require knowledge of a constructor. – chacham15 Sep 12 '14 at 03:50
  • @ElliottFrisch it is meant to be a pool. do you know of any pools for android that act like caches? – chacham15 Sep 12 '14 at 03:51
  • @chacham15 [What is Object Pooling in Java?](http://stackoverflow.com/q/4921642/2970947) – Elliott Frisch Sep 12 '14 at 03:53

0 Answers0