Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
817 views
in Technique[技术] by (71.8m points)

generics - The syntax <T extends Class<T>> in Java

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. In the declaration maxStackclass<T extends Comparable <T>> you have already expressed the bounds on T. So you do not need it again.

  2. Reason same as above. No need to specify bounds on the same type parameter again.

  3. <T extends Comparable<T>> means that T must implement the Comparable interface that can compare two T instances. While <T extends Comparable> means T implements Comparable such that it can compare two Objects in general. The former is more specific.

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>>


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...