简体   繁体   中英

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.

Try this:

public class Test {
    public static void main(String[] args) throws java.lang.Exception {
        NavigationTree<DrawerListItem<Screen>> nt = new NavigationTree<>();
        nt.insert(new DrawerListItem<Screen>(), new DrawerListItem<Screen>());
    }

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

    private static class DrawerListItem<T> extends BaseListItem<T> {}
    private static class BaseListItem<T> {}
    private static class Screen extends BaseData {}
    private static class BaseData {}
}

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM