TLD
TLD

Reputation: 8135

Generic method in java

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

Why do I need <T> in method public <T> T pop() throws Exception?

Upvotes: 1

Views: 292

Answers (2)

Lukas Eder
Lukas Eder

Reputation: 220877

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() {
   // ...

Upvotes: 0

Manoj
Manoj

Reputation: 5612

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.

Upvotes: 1

Related Questions