0

I found this in a java book and would like to understand why am I getting the error as outlined below:

public class Wildcard<V> {

    V value;

    public Wildcard(V value) {
        super();
        this.value = value;
    }

    public V getValue() {
        return value;
    }

    public void setValue(V value) {
        this.value = value;
    }

    public boolean sameObj(Wildcard<? extends V> v1, MyComparator<V> comparator) {
        return comparator.compare(this.value, v1.value);
    }

    public static void main(String[] args) {

        Wildcard<Integer> iTest = new Wildcard<Integer>(10);
        Wildcard<Number> nTest = new Wildcard<Number>(10);
        nTest.sameObject(iTest, new MyComparator<Number>() {
            public boolean compare(Number o1, Number o2) {
                return o1 == o2;
            }
        });
    }
}

interface MyComparator<V> {
    public boolean compare (V value,V value2) ;
}

The syntax error that appears on the line nTest.sameObject is:

The method sameObject(Wildcard<Integer>, new MyComparator<Number>(){}) is undefined for the type Wildcard<Number>

Since the method is being called on class Wildcard parameterized with Number, the first parameter to sameObject function can be anything that extends V (Number in this case) and the parameter to the function that appears next should be V (a Number in this case). Hence it should be a legal call. Why is it not a legal call?

2 Answers 2

6

This is likely a typo. sameObj != sameObject.

2
  • Good catch, that was hard to see. Mar 29, 2015 at 21:51
  • Yes, indeed. Corrected. Thanks Mar 29, 2015 at 21:57
1

As col6y pointed out, you should rename the sameObj method to sameObject.

As further improvement, I suggest that you change the method's signature as follows

public boolean sameObject(Wildcard<? extends V> v1, MyComparator<? super V> comparator)

It then follows the PECS (producer extends, consumer super) rule. This enables you, in that specific case, to invoke the method sameObject with a comparator that was designed for a super type of V.

For more information on PECS you can read Effective Java by Joshua Bloch, or take a quick look at this question on SO.

Not the answer you're looking for? Browse other questions tagged or ask your own question.