Creating an object without knowing a specific type

I am creating the following java class.

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

The idea is that a user of this class will tell me which objects are stored in the collection and in the actual storage. So M can be a simple Hashmap or LinkedHashmap.

I have two questions: How do I create an instance of M inside my class? Is it possible?

AND

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

+1
java generics design-patterns
source share
2 answers

You cannot do this the way you are configured due to type erasure. You can remove it by passing you a class.

Let it read:

Create an instance of a generic type in Java?

+1
source share

Creating a hashmap is very simple, you just pass the generic types through - or even use a diamond notation and do it for you.

 M m = new HashMap<>(); 

The complication is that you also want to choose the type of Card. There are several ways to do this:

  • You can use the Factory template and pass in a Factory object that creates cards on demand.

  • You can create a map outside the class and pass it in the constructor.

  • Have an abstract method for creating a map. When creating an instance of a class, people implement this abstract method and generate a map for it.

In the second question, there is no way to know if there is much more detail about what you are doing. This is an architectural solution and most likely will not fit into the Q and A stack overflows. It all seems a bit dirty, although you expose a lot of the internal behavior of the classes. You should probably think more about the behavior you want and the interface to provide it, rather than implementation details.

For example, you might have enum { UNSORTED, INSERTION_ORDER, etc } , and then create an instance of the right map based on this listing.

+1
source share