简体   繁体   English

我如何在语法上正确地实现具有类型的接口<K extends Comparable<K> ,V&gt;?

[英]How do I syntaxcially correctly implement an interface with type<K extends Comparable<K>, V>?

在此处输入图片说明

K and V are guarantee to be either String or Integer. K 和 V 保证是字符串或整数。 I've use generics quite a few times, but never <K extends Comparable<K>, V> , so I am struggling right now.我已经多次使用泛型,但从来没有<K extends Comparable<K>, V> ,所以我现在很挣扎。

When you implement a generic interface, you should always specify the type arguments.当你实现一个泛型接口时,你应该总是指定类型参数。 You can get away with not specifying them, but then you are using raw types, which you shouldn't .您可以不指定它们,但是您使用的是原始类型, 而您不应该使用原始类型。

When you do specify them, you also need to specify them in a valid way.指定它们,你还需要一个有效的方式来指定。

First option is wrong because of two reasons:由于两个原因,第一个选项是错误的:

  • When you specify the type arguments, you never rewrite the bounds on that argument, so writing K extends Comparable<K> is wrong当您指定类型参数时,您永远不会重写该参数的边界,因此编写K extends Comparable<K>是错误的
  • K and V are not defined anywhere. KV没有在任何地方定义。

Second option is wrong because you rewrote the bounds on K .第二个选项是错误的,因为您重写了K的边界。 This option differs from the first option in that K and V are defined here - K and V are the type arguments of Son .在第一选择此选项不同KV这里定义- KV是类型参数Son

Third option compiles, but it uses raw types, which kind of defeats the purpose of using generics in the first place.第三个选项编译,但它使用原始类型,这首先违背了使用泛型的目的。

Ideally, you would write something like:理想情况下,您会编写如下内容:

class Son<K extends Comparable<K>, V> implements Father<K, V> {

}

Note how I did not rewrite the bounds, and defined K and V as the type arguments for Son .请注意我没有重写边界,并将KV定义为Son的类型参数。

Alternatively, specify a concrete type:或者,指定一个具体类型:

class Son implements Father<String, Integer> {

}

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

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