Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generic List parameter not possible?

Tags:

java

generics

i have a simple method that takes a generic List parameter but for some reason my IDE(Eclipse) states how it cannot be resolved?

Am i doing something wrong here

private OnClickListener removeFieldListener(final LinearLayout layout,
            List<T> viewList) {

        return new OnClickListener() {

            @Override
            public void onClick(View v) {
                int indexToDelete = layout.indexOfChild(v);

            }
        };
    }
like image 315
Jonathan Avatar asked Nov 12 '10 10:11

Jonathan


Video Answer


2 Answers

In that case, the T parameter has to be defined somewhere. As I guess your class does not declares this parameter, you have to put it in your method declaration, like

private <T> OnClickListener removeFieldListener(final LinearLayout layout,
        List<T> viewList) {

But this will only move the problem to the caller of this method ...

like image 75
Riduidel Avatar answered Oct 11 '22 03:10

Riduidel


Riduidel is right in that the problem is that you haven't declared the T anywhere.

Depending on what you want to do with the contents of the list, chances are you can just use a wildcard. List<?> viewList would work if you're only pulling Objects out of it; or List<? extends IListener> will allow you to get IListeners out of it, etc.

In general, you don't need a generic parameter if it only appears once within your method, and you should use a wildcard instead. If it does appear multiple times, for example you remove things from the list and assign them to variables of type T, then you do indeed need the wildcard and you should parameterise your method as Riduidel suggests.

like image 44
Andrzej Doyle Avatar answered Oct 11 '22 03:10

Andrzej Doyle