Generics: enter a variable?

In order to be able to replace a specific implementation, it is generally known that

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

instead

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

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

Well ... it's all nice and nice, but since I cannot directly initiate the List, so I will need to enter

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

which makes the previous template completely pointless. What if I now want to replace the LinkedList implementation with an ArrayList? It is required to change it to two positions.

Is it possible to have something like this (I know the syntax is completely wrong)?

public class MyClass<T>
{
    Type myListImplementation = ArrayList;

    List<T> myList = new myListImplementation<T>();

    public List<T> getSpecificList()
    {
        return new myListImplementation<T>();
    }
}

"ArrayList" "LinkedList", . , , " ". .

- ? ^

Atmocreations

+3
9

- factory pattern . , factory.

, :

 List<T> createList() {
     return new ArrayList<T>();
 } 

 List<T> myList1 = createList();
 List<T> myList2 = createList();

, , , createList(), .

List<T> createList() {
    return new LinkedList<T>();
}
+14

Erm - , , , ( ).

( ) , . , ( , , ..). - myList , , , .

, , ( ), . factory; factory, , myList

List<T> myList = getSpecificList();

- , , , :

public class MyClass<T>
{
    Class<? extends List<T>> myListClass = ArrayList.class;

    List<T> myList = myListClass.newInstance();

    public List<T> getSpecificList()
    {
        return myListClass.newInstance();
    }
}

- , , ( ) ...

: , , , , , .; -)

+8

, LinkedList ArrayList? .

, . . LinkedList, ArrayList.

+5

, polymorphism.

List ( List<T>) ArrayList ( ArrayList<T>) , List , ArrayList - . , , .

, List? , factory, .

, , ( "" ) . , ( "" ) , ( ). , , ArrayList LinkedList - .

+3

"" - , , , , List, . , :

  • , newList(), List. , , ArrayList LinkedList, newList(). getSpecificList()
  • , List: List :

    public MyClass (Class <? extends List <T> gt;) {...}

№ 2 List, , , , .

0

"" "" , . , .

, :

 ArrayList<T> createArrayList();

- . "" - , , , List-ishness, .

0

I ( , ), - :

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

- <T>. , , .

0

If you do not initialize myList, you only need to make a difference in one place. Unless, of course, you need to use any of the methods unique to ArrayList ...

List<AnyType> myList = getSpecicList();

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

How about this?

public class MyClass<T>
{
    List<T> myList = this.getSpecificList();

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

Now you only need to change the type in one place.

0
source

Source: https://habr.com/ru/post/1719640/


All Articles