开发者

Generic method in java

public class Stack<T> {
  public <T> T pop() throws Exception;
}

Why do I need <T&g开发者_JS百科t; in method public <T> T pop() throws Exception?


You do not need to put there public T pop() throws Exception works fine.

More detailed explanation is available here http://download.oracle.com/javase/tutorial/java/generics/genmethods.html

It seems just a convention and preference, Java infers the Type even if you do not provide the type in the method.


You probably have a warning that your method's generic type parameter T is hiding the generic type T of the class. Check out the java.util.Stack class. It does it differently

public
class Stack<E> extends Vector<E> {
   // ...
   public synchronized E pop() {
   // ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜