3

In “Java the Complete Reference” by Herbert Schildt (10th edition), in chapter 14 on Generics there is the following example of a generic method that checks if an object is in an array:

class GenMethDemo {

    static <T extends Comparable<T>, V extends T> boolean isIn(T x, V[] y) {
        . . .
    }

    . . .
}

I don’t understand why V extends T is used here.

Why do we allow array’s type to be the subclass of the object that we check for membership? Shouldn’t it be the other way around?

0

2 Answers 2

2

In this case V needs to be a subclass of T as you want to call Comparable methods on the V[]. If you would allow V to be a super type of T (e.g. an Object[]) you can not call compareTo as these methods are not implemented.

Sign up to request clarification or add additional context in comments.

2 Comments

Ah, I see. Aren’t we restricting outselves a little? In a sense that we won’t be able to use this method to check if a subclass object is in an array of superclass objects?
But why the second type parameter is needed at all? Why not simply T[] y?
2

After some tinkering, I am able to answer my question.

Indeed, as @m-le-rutte has stated, V needs to extend T to ensure that they both implement Comparable<T>. However, this is somewhat illogical, as it allows us to check superclass objects for membership in subclass arrays, but not the opposite.

Here’s how to reverse the situation:

public class GenMethDemo {
    static <V extends Comparable<V>, T extends V> boolean isIn(T x, V[] y) {
        . . .
    }

    . . .
}

As I have found out, the order of type parameters needs not to be the same as the order of method parameters.

Whether you can create a single declaration that allows both T extends V and V extends T as long as they both implement Comparable<> of the senior one, I do not know, but doubt.

ADDITION:

As @lexicore mentions, the following seems to work as well:

public class GenMethDemo {
    static <T extends Comparable<T>> boolean isIn(T x, T[] y) {
        . . .
    }

    . . .
}

And it too supports x being a subtype of y[].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.