bmanicus131
bmanicus131

Reputation: 53

Type Bounds with Comparable Interface in Java

In JDK 11 I'm creating a generic class called "Collection" such that whatever type is provided for the type parameter must implement the Comparable interface. The class declaration is currently as follows:

public class Collection <T extends Comparable<T>> 

Originally I thought the class declaration should be this:

public class Collection <T implements Comparable<T>> 

but JDK didn't like that.

So my question is why the class declaration is the former rather than the latter. Don't we extend classes and implement interfaces?

Upvotes: 1

Views: 598

Answers (3)

Brian Goetz
Brian Goetz

Reputation: 95446

With respect to the syntax of bounds declaration, the language architects who added generics in Java 5 faced the following choice:

  • Mirror the declaration structure (with separate extends and implements bounds), or
  • Choose one form for upper-bounded types (e.g., T extends Foo, T <: Foo, etc.)

The latter was (sensibly, IMO) viewed as the more pragmatic choice, as at the point of declaring a type variable, whether the supertype happens to be a class or an interface is not material, and having a fussy syntax that required clients to use exactly the right keyword (and would have made compound bounds like <T extends ArrayList implements Serializable> even uglier) would likely be viewed as just making things harder to use with no actual benefit to either writers or readers of code.

Such decision often come about as a language is evolved, where strict consistency with precedent would only make things more difficult for no good benefit, and so language designers sometimes (after carefully considering the pros and cons of both alternatives) choose to break with precedent for the sake of a better result.

Upvotes: 3

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

Would you therefore want implements E or extends E, given that E may be a class or an interface? Unless you want a third keyword (possibly context-sensitive) then it doesn't make sense to distinguish.

Upvotes: 0

rzwitserloot
rzwitserloot

Reputation: 103254

  1. Collection is already in java.util. Creating another class with that name is going to confuse everybody; I suggest you pick something else.

  2. Generics is about types in general. The word extends is used, and this kinda mirrors the same use of that keyword in, for example, class Foo extends Bar, but it's not quite the same meaning. The point is, the spec says it is extends and not implements regardless of what comes after, and there's not much point in going any further than 'spec says so' on this one.

Upvotes: 0

Related Questions