Java – generics: input variables?

In order to be able to replace a specific implementation, it is usually known to write

List<AnyType> myList = new ArrayList<AnyType>();

replace

ArrayList<AnyType> myList = new ArrayList<AnyType>();

This is easy to understand, so you can easily change the implementation from ArrayList to LinkedList or any other type of list

Well... It's all good, but since I can't instantiate "list" directly, I need to enter it

public List<AnyType> getSpecificList()
{
    return new ArrayList<AnyType>();
}

This makes the previous model meaningless What if I want to replace the implementation with LinkedList instead of ArrayList now? It needs to be changed in two places

Is it possible that there is such a thing (I know the grammar 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 will allow me to simply change the word "ArrayList" to "LinkedList" and everything is fine I know that these two lists may have different constructors, which won't work "as is" I really don't want to add a second type parameter to specify the list implementation being used

Is there any clean mechanism to solve this problem^

Thank you for your greetings to atmocreations

Solution

Why not use some factory pattern instead of directly instantiating a specific list implementation You then need to change the list implementation at a location within 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 you need a linked list, you just need to change the implementation of createlist (), leaving the rest of the code unchanged

List<T> createList() {
    return new LinkedList<T>();
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>