0

As the title says, I am wondering what the difference between those functions is. Why should/shouldn't I provide the <T> in foo2

public class Base<T> {

    public T[] foo(int i){
        /*Do something*/

    }

    public <T> T[] foo2(int i){
        /*Do something*/
    }

}
jhamon
  • 3,603
  • 4
  • 26
  • 37
MrT
  • 3
  • 1

1 Answers1

5

The T of your second function hides the type parameter T of your class. This means that T in the second function referes to a different type T. This naming is confusing and should be avoided.

You can, of course, do this if you actually want to refer to a different generic type, but you should name the type parameter differently. The following example is equivalent to yours but does not hide T defined in Base:

public class Base<T> {

    public T[] foo(int i){
        /*Do something*/

    }

    public <S> S[] foo2(int i){
        /*Do something*/
    }
}
Alex R
  • 3,139
  • 1
  • 18
  • 28