1

I am creating following java class.

class EntityCollection <E extends Entity, M extends Hashmap<?,E>> {
}

The idea is that the user of this class will tell me what type of objects to save in the collection and the actual store. So M can be simple Hashmap or LinkedHashmap.

I have two questions here: How would I instantiate M inside my class? Is it possible?

AND

Is this a good approach or should I take some StoreFactory that would return me the store to use? Should I take that in the constructor of this class?

ata
  • 8,853
  • 8
  • 42
  • 68

2 Answers2

1

You can't do this the way you're set up due to type erasure. You can pull it off by having them pass the class to you.

Give this a read:

Create instance of generic type in Java?

Community
  • 1
  • 1
candied_orange
  • 7,036
  • 2
  • 28
  • 62
  • Yes creating the collection, but of type user specify in M – ata May 20 '14 at 13:25
  • @Tim B I'm reacting to the "Instantiate M" requirement. A factory created by the user (not the entitycollection author) can also abstract away knowledge of the concrete type but so can simple dependency injection. – candied_orange May 20 '14 at 13:29
1

Creating the hashmap is easy, you just pass the generic types through - or even use the diamond notation and have it done for you.

M m = new HashMap<>();

The complication is that you want to also be able to select the type of the Map. That can be done in a number of ways:

  • You could use the Factory pattern and pass in a factory object that creates the maps on demand.

  • You could generate the Map outside the class and pass it in on the constructor.

  • Have an abstract method to create the map. When creating an instance of the class people would implement that abstract method and generate the map for it.

For the second question there's no way to know without a lot more detail of what you are doing. That's an architectural decision and would most likely not fit into a stack overflow Q & A. This all seems a bit messy though, you are exposing a lot of the internal behavior of the classes. You would probably be better off thinking more about the behavior you want and the interface to provide that rather than the details of implementation.

For example you could have an enum { UNSORTED, INSERTION_ORDER, etc } and then instantiate the right Map based on that enum.

Tim B
  • 40,716
  • 16
  • 83
  • 128
  • I think the OP wants to be able to dynamically construct the sub-class of `HashMap` requested by the caller. I.e. I could demand he use a `LinkedHashMap`. – Duncan Jones May 20 '14 at 13:23
  • This thing is, if user want to create a LinkedHashmap, would M m = new Hashmap<>(); works? – ata May 20 '14 at 13:24
  • @Duncan You are right of course, I missed that. I've amended my answer. – Tim B May 20 '14 at 13:26