Question

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?

Était-ce utile?

La solution

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.

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top