简体   繁体   中英

Java generics extends syntax

Can someone please explain me this class definition statement

public class BinarTree<Type extends Comparable<Type>> {...

I completely understand the purpose of it but not the syntax. According to me it should be just

public class BinarTree<Type extends Comparable> {...

What's the meaning of

<Type extends Comparable<Type>> ?
                         ^^^^

Comparable is a generic interface. The reason behind that is to avoid casting to a specific type in the Comparable#compareTo(...) method.

So if a Type extends Comparable<Type> this would mean that the Type will derive a method with signature

public int compareTo(Type t1)

instead of

public int compareTo(Object o1)

The interface Comparable is itself a template. So what you have there is a template with a parameter that must extend a template. And specifically it must extend a template that received the extending class as a parameter.

Comparable is a template for interfaces that implement an order relationship and implement the method int compareTo(TYPE o) . So it's normal to define a class:

  class FooBar implements Comparable<FooBar> {...

A binary tree wouldn't work for a class that was declared:

  class FooBar implements Comparable<Snafu> {...

That's because you would be able to compare FooBar s to Snafu s but not each other.

In

public class BinarTree<Type extends Comparable>{...

Type can be any Comparable , also Comparable<Integer> or Comparable<OtherType> . If this is what you want, it is fine. Most times, I think you know what you want to compare exactly, so specialize the Comparable to Comparable<Type>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM