简体   繁体   English

Java泛型扩展语法

[英]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. Comparable是通用接口。 The reason behind that is to avoid casting to a specific type in the Comparable#compareTo(...) method. 其背后的原因是避免在Comparable#compareTo(...)方法中强制转换为特定类型。

So if a Type extends Comparable<Type> this would mean that the Type will derive a method with signature 因此,如果Type extends Comparable<Type>这意味着该Type将派生带有签名的方法

public int compareTo(Type t1)

instead of 代替

public int compareTo(Object o1)

The interface Comparable is itself a template. 接口Comparable本身就是一个模板。 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) . Comparable是用于接口的模板,这些接口实现顺序关系并实现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. 这是因为您将能够将FooBarSnafu进行比较,但不能相互比较。

In

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

Type can be any Comparable , also Comparable<Integer> or Comparable<OtherType> . Type可以是任何Comparable ,也可以是Comparable<Integer>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> 大多数时候,我认为您知道要精确比较的内容,因此将Comparable改为Comparable<Type>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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