eliocs
eliocs

Reputation: 18827

Java generics collection doubt

I'm having trouble with a generics. I have defined the following static method:

public static <E extends Number> List<E> group(E ... numbers) {
    return Arrays.asList(numbers);
}

I understand why this works:

List<Integer> ints = group(1, 2, 3);

But what do I have to change in my method signature to make this work:

List<Number> ints = group(1, 2, 3);

Or should I just call the group method specifying the Number type as:

List<Number> ints = MyClass.<Number>group(1, 2, 3);

Thanks in advance.

Upvotes: 3

Views: 173

Answers (2)

jacobm
jacobm

Reputation: 14035

You need to explicitly specify Number as the type argument, as you suggested.

List<Number> ints = MyClass.<Number>group(1, 2, 3);

Upvotes: 2

Snicolas
Snicolas

Reputation: 38168

You won't be able to do get a List<Number>.

If your method group(1,2,3) return a List<Integer>, and you said that worked, so this expression is of type List<Integer>.

And List<Integer> is not a List<Number>. Inheritance means specialization, so if your List<Integer> would be a kind of List<Number> you could add Doubles to your List<Integer> (as the super class can do it, subclass can do it too). And this is wrong. This not a casting problem, it would just postpone your compile problem to runtime. The problem is logical and quite a paradox for humans, but that's the way collection and inheritance work.

So, if you really want to get a List<Number> I suggest you define a second method :

public static List<Number> groupAsNumbers(Number ... numbers) {
    return Arrays.asList(numbers);
}

Regards, Stéphane

Upvotes: 2

Related Questions