2

I have the following problem when using java generic. Basically I need to do a conversion from an list of subtype to a list of its supertype, and I defines a method like this:

public static <T> List<T> getList(List<? extends T> input) {
    ArrayList<T> list = new ArrayList<T>();
    list.addAll(input);
    return list;
}

However I'm not sure how I can invoke this method? Given type A, B extends A:

List<A> alist = getList(List<B> blist);

has a mismatch type, because in this case I only supply B's type information to the method invocation.

How can I invoke the method with the type information A supplied?

Thanks.

2 Answers 2

5
List<B> blist = ...
List<A> alist = ClassName.<A>getList(blist);

Note that you could also just use ArrayList's constructor here:

List<A> alist = new ArrayList<A>(blist);
Sign up to request clarification or add additional context in comments.

5 Comments

I didn't know that you can do ClassName.<A>getList(blist) in java
@ColinD Shouldn't it be ClassName.<A, B>getList(blist)? Specifying both generic types? I seem to need that on my Java 6 compiler at least...
I think that the "just call the constructor" route is the way to go.
@Greg: No, the method only has one generic type parameter, T, and as such can only accept one type argument, A in this case. A matters because it's the return type we want. B doesn't matter so much other than that it must be a subtype of A.
@ColinD: ah, yes, you're correct. I was playing around with some code for this question and at one point I had a method that had two type parameters, but both don't need to be named, one can be a wildcard, my bad, thanks (I still think that just calling the constructor is likely the best approach ;)
-1

How about

public static void <T, S extends T> List<T> getList(List<S> input)

2 Comments

That doesn't add anything over the List<? extends T> version unfortunately. Calls still fail to compile without specifying type arguments.
that's right: there's no point to add S if it's only used once

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.