What is the problem with this Generics related Java code?

interface Addable<E> {
    public E add(E x);
    public E sub(E y);
    public E zero();
}

class SumSet<E extends Addable> implements Set<E> {

    private E element;

    public SumSet(E element) {
        this.element = element;
    }

    public E getSum() {
        return element.add(element.zero());
    }
}

It element.add()does not seem to return E extends Addable, but rather Object. Why is this? Does this have anything to do with the fact that Java does not know at run time what the types of objects really are, so does it just assume that they are objects (which requires listing)?

thank

+5
source share
4 answers

It should be:

class SumSet<E extends Addable<E>> implements Set<E> {

, SumSet E, Addable ( Addable<Object>). Addable Addable<E>, , add, sub zero E E ( Object).

, E SumSet E. :

class SumSet<T extends Addable<T>> implements Set<T> {

    private T element;

    public SumSet(T element) {
        this.element = element;
    }

    public T getSum() {
        return element.add(element.zero());
    }
}

.

+5

Try:

class SumSet<E extends Addable<E>> implements Set<E> {

, , , , Addable SumSet . Addable SumSet :

interface Addable {
  Object add(Object x);
  Object sub(Object y);
  Object zero();
}

, Object E, . . raw? Java Generics.

public .

+9

<E extends Addable<E>>, <E extends Addable>.

, raw- () .

+3

SumSet, Set, , , , , .

public static <T extends Addable<T> > T sum(Set<T> set)
{
    T sum = null;
    for (T t : set)
    {
        if (sum == null)
        {
            sum = t;
        }
        else
        {
            sum = sum.add(t);
        }
    }
    return sum;
}
0

All Articles