Jono
Jono

Reputation: 18128

Java generic List parameter not possible?

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);

            }
        };
    }

Upvotes: 12

Views: 33852

Answers (2)

Andrzej Doyle
Andrzej Doyle

Reputation: 103837

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.

Upvotes: 15

Riduidel
Riduidel

Reputation: 22308

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 ...

Upvotes: 21

Related Questions