语法< T extends Class< T>>在Java中 [英] The syntax <T extends Class<T>> in Java
问题描述
我对以下内容有一些想法:
public interface MaxStack< T extends Comparable< T>>
<1>为什么实现 MaxStack
应该这样写:
public class MaxStackclass< T extends Comparable< T>>实施MaxStack< T>
而不是 public class MaxStackclass< T extends Comparable< T>>实现MaxStack< T扩展Comparable< T>>
?
2-为什么这个类的私有变量使用泛型,只能写成< T>
,而不是< code>< T extnds Comparable< T>> ?例如,私人列表< T> stack = new ArrayList< T>();
<3>
< T extends Comparable< ; T>>
和< T扩展Comparable>
- 如果我需要比较类中的元素,编辑:我认为3的问题在于它可能允许插入一个以第二种方式定义的列表,使其具有不同的元素,这些元素都是从可比,然后当我想比较它们时,这是不可能的,因为我们无法将字符串与Integer进行比较,都是从Comparable扩展而来。 解决方案 -
在声明
maxStackclass< T extends Comparable< T>>
在T
上。所以你不需要它。 -
原因与上面相同。
-
< T extends Comparable< T>>
意味着T
必须实现Comparable
接口,它可以比较两个T
实例。
意味着< T扩展Comparable> T
implementsComparable
这样它就可以比较两个Object
。如果我需要比较我班中的元素,那么我们就可以比较一下这些元素。 ,两者都可以, In the declaration
maxStackclass<T extends Comparable <T>>
you have already expressed the bounds onT
. So you do not need it again.Reason same as above. No need to specify bounds on the same type parameter again.
<T extends Comparable<T>>
means thatT
must implement theComparable
interface that can compare twoT
instances. While<T extends Comparable>
meansT
implementsComparable
such that it can compare twoObject
s in general. The former is more specific.
不可以?
嗯,技术上你可以 使用两者的结果。但是对于声明< T extends Comparable>
,它将涉及不必要的转换,您可以避免使用类型安全的< T extends Comparable< T> >
I have couple of thoughts regarding the following:
public interface MaxStack<T extends Comparable <T>>
1-Why does the class that implements MaxStack
should be written like this:
public class MaxStackclass<T extends Comparable <T>> implements MaxStack<T>
and not public class MaxStackclass<T extends Comparable <T>> implements MaxStack<T extends Comparable <T>>
?
2- why do the private variables of this class, when I use generics, should be written only with <T>
and not with <T extnds Comparable<T>>
? For example, private List<T> stack= new ArrayList<T>();
3-What is the difference between <T extends Comparable<T>>
and <T extends Comparable>
- if I need to compare bewteen elements in my class, both will be O.K, no?
Edit: I think that thee problem with 3 is that maybe it allows to insert of a list that was defined in the second way to have different elements which all extends from comparable and then when I want to compare them, it won't be possible, since we can't compare String to Integer, both extend from Comparable.
if I need to compare bewteen elements in my class, both will be O.K, no?
Well, technically you can achieve the same result using both. But for the declaration <T extends Comparable>
it will involve unnecessary casts which you can avoid using the type safe <T extends Comparable<T>>
这篇关于语法< T extends Class< T>>在Java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!