user1501247
user1501247

Reputation: 326

Generic return type - unable to compile

I'm reading the Oracle Generics tutorial, and I'm having a problem getting the following code to work:

import java.util.*;
public class GenericReturn {
    public static void main(String[] args){
            Integer index = 1;
            ArrayList<Integer> AL = new ArrayList<>();
            AL.add(10);
            AL.add(20);
            AL.add(30);
            Number s = choose(index, AL);
            System.out.println(s);
    }
    static <T, U, S> S choose(T a1, U a2) { return a2.get(a1); }
}

It won't compile The errors are:

javac GenericReturn.java 
GenericReturn.java:12: error: cannot find symbol
    static <T, U> T choose(T a1, U a2) { return a2.get(a1); }
                                                  ^
symbol:   method get(T)
location: variable a2 of type U
where T,U are type-variables:
T extends Object declared in method <T,U>choose(T,U)
U extends Object declared in method <T,U>choose(T,U)
1 error

Can anyone please help me out here?

Someone's almost certain to want to mark this as a duplicate, but please don't - Generics is hard enough without ploughing through another similar question which doesn't quite cover what you need to know!

Upvotes: 0

Views: 57

Answers (1)

Chetan Kinger
Chetan Kinger

Reputation: 15212

Change :

static <T, U, S> S choose(T a1, U a2) { return a2.get(a1); }

To :

static <U extends List<S>, S> S choose(Integer a1, U a2) { return a2.get(a1); }

Or a more simplified version :

static <S> S choose(Integer a1, List<S> a2) { return a2.get(a1); }

That being said, all Collection classes in Java are already generic so there is no need to write such a wrapper method in the first place.

Upvotes: 2

Related Questions