开发者

Generic method in java

开发者 https://www.devze.com 2023-02-04 00:21 出处:网络
public class Stack<T> { public <T> T pop() throws Exception; } Why do I need <T&g开发者_JS百科t; inmethod public <T> T pop() throws Exception?You do not need to putthere public
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

精彩评论

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