Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Assigning specified type to generic type

Im trying to understand the following code.

class Test<E extends SubTest>
{
    List<Vector<E>> links;

    Test()
    {
        links = MyStaticClass.aList;
        // Where aList is static ArrayList<Vector<SubTest>>;
    }
}

How come assigning the following ArrayList to links List gives an error. Souldnt it understand the assignment considering i extended E with SubTest.

When I have a parameter T t; i can access t properties, but i cant do the said assing. Wouldnt List<Vector<T>> links expect to get ArrayList<Vector<SubTest>> anyway ?

like image 612
Sterling Duchess Avatar asked Aug 23 '26 06:08

Sterling Duchess


1 Answers

You're misunderstanding the error.

The actual problem is that E is not the same as SubTest.

If you make an instance of Test<SubSubTest> (where SubSubTest inherits SubTest), your code would try to put a collection of SubTests (which can hold any derived class) into a variable of type List<Vector<SubSubTest>> (which can only hold SubSubTest).

like image 152
SLaks Avatar answered Aug 24 '26 19:08

SLaks