Generics: Type as variable?
generics, java
Solution
Why not use some kind of factory pattern instead of instantiating a specific list implementation directly. Then you need to change list implementation only in one place, inside the factory method.
For example you start with:
List<T> createList() {
return new ArrayList<T>();
}
List<T> myList1 = createList();
List<T> myList2 = createList();
Later, if you decide that you need a linked list instead, you just change the implementation of createList() and the rest of your code stays the same.
List<T> createList() {
return new LinkedList<T>();
}
Problem
In order to be able to substitute a specific implementation, it is commonly known to write ``` List<AnyType> myList = new ArrayList<AnyType>(); ``` instead of ``` ArrayList<AnyType> myList = new ArrayList<AnyType>(); ``` This is easy to understand, this way you might change the implementation from ArrayList to LinkedList or any other kind of List with ease. Well... this is all good and nice, but as I cannot instanciate "List" directly, I therefore would be required to type ``` public List<AnyType> getSpecificList() { return new ArrayList<AnyType>(); } ``` which makes the previous pattern quite senseless. What if I now want to replace the implementation by an LinkedList instead of an ArrayList? It would be required to change it on two positions. Is it possible to have something like this (I know the syntax is absolutely incorrect)? ``` public class MyClass<T> { Type myListImplementation = ArrayList; List<T> myList = new myListImplementation<T>(); public List<T> getSpecificList() { return new myListImplementation<T>(); } } ``` This would allow me to simply change the word "ArrayList" to "LinkedList" and everything is fine. I know that both lists may have different constructors and this would not work "as is". And I don't really want to add a second type-parameter for specifying the list-implementation that is being used. Is there any clean mechanism to fix this?^ Thanks in advance and best regards Atmocreations