kmort
kmort

Reputation: 2928

Why must I cast this generic type?

I am trying to make a node that is Comparable, and only holds objects that are Comparable.

From what I understand of Java, the member variable value should be of type E, so later when I access it in compareTo(), it should still be of type E, and shouldn't need casting, but the compiler informs me this is not the case with:

incompatible types: java.lang.Comparable cannot be converted to E.

I think it should already be type E. Why must I cast o.value to type E in the first usage, but not in the second? What am I missing?

The code is below.

public class fakenode<E extends Comparable<E>> implements Comparable<fakenode> {
 public E value;

 fakenode (E value)
 {
    this.value = value;
 }

 @Override
 public int compareTo(fakenode o) {
    value.compareTo((E)o.value); // Why must I cast o to type E here?
    o.value.compareTo(value);    // This one works just fine

    return -1;
 }

Upvotes: 0

Views: 66

Answers (1)

Eran
Eran

Reputation: 393781

You left out the generic type parameter E from two of the places where you use the type fakenode.

It should be:

class fakenode<E extends Comparable<E>> implements Comparable<fakenode<E>> { // first change
    public E value;

    fakenode (E value)
    {
        this.value = value;
    }

    @Override
    public int compareTo(fakenode<E> o) { // second change
        value.compareTo(o.value);
        o.value.compareTo(value);

        return -1;
    }
}

I suppose this is not the actual logic of your compareTo method, though, since it always returns -1.

Upvotes: 4

Related Questions