Search code examples
javagenericstype-parameter

passing arguments to method with generics in java


I have the following structure of classes and methods :

public class NavigationTree<T extends BaseListItem<? extends BaseData>> {
    public boolean insert(final T parent, final T child){
    }
}

public class Screen extends BaseData {
}

public class DrawerListItem<T> extends BaseListItem<T>{
}

This is what I am calling from one of my other classes :

mCurItems.insert(new DrawerListItem<Screen>(null, null),
                 new DrawerListItem<Screen>(screen.name, screen));

The compilers throws the following error :

Error: incompatible types: DrawerListItem cannot be converted to CAP#1 where CAP#1 is a fresh type-variable:CAP#1 extends BaseListItem from capture of ? extends BaseListItem

I do not understand why this should be wrong. DrawerListItem extends BaseListItem and Screen extends BaseData. I have tried reading the other posts around generic types and type params but none of them seem to address this issue.


Solution

  • I figured out the solution. In my DrawerListItem declaration I had declared it as

    public class DrawerListItem<T> extends BaseListItem<T>{
    }
    

    Whereas the NavigationTree was expecting:

    <T extends BaseListItem<? extends BaseData>>
    

    Which essentially means :

    <DrawerListItem<? extends BaseData>>
    

    in this case.

    And hence the error was basically saying that the template type declared vs template type required are different and hence the error. Hope this helps someone else. Thanks everyone for the help!