Reputation: 69249
I have a class like this:
public class SpiralGenerator<E extends Number> implements Iterator<List<E>> {
private void generate(int pos, E... array) {
if (pos == array.length) {
List<E> list = new ArrayList<>();
list.addAll(Arrays.asList(array));
currentResults.add(list);
return;
}
generate(pos + 1, array);
array[pos] = -array[pos];
}
}
However it does not allow array[pos] = -array[pos]
. If I use Integer
instead of E extends Number
it works fine.
Error message:
bad operand type E for unary operator '-'
where E is a type-variable:
E extends Number declared in class SpiralGenerator
Why does the current approach not work, and how could I solve it?
Upvotes: 1
Views: 172
Reputation: 1499770
Basically, Number
doesn't have any sort of "give me the negative value" operation - and that's what you want.
You could write your own method, which special-cased each kind of number you're interested in - but you can't just use the -
operator. The method would be pretty ugly, and not provably type-safe. It may be all you've got though.
Upvotes: 4
Reputation: 9954
With you code you rely on boxing/unboxing. This is not supported by all Number
classes (e.g. BigInteger
).
Therefore the compiler does not allow this.
Upvotes: 2