Why is <T> required in method signature, when a method takes generic params

Hello Everyone,

I'm new to Generics and I'm trying to understand Generics with respect to declaring a method with generic parameters.

I know how to write the code for this, below is an example of what I've tried so far and it works.

However, I don't really understand why I'm supposed to have something like <T> just before the method signature , shown below.

If I remove the <T> I get , a compile time error as shown in the comment below.

publicclass GenericsTest{

publicstaticvoid main(String[] args){

myGenericsMethod("Print a string");

myGenericsMethod(8);

myGenericsMethod(45.3F);

myGenericsMethod(1244);

}

/*

This gives an error "cannot find symbol class T"

if the <T> is removed

*/

privatestatic <T>void myGenericsMethod(T someGenericParameter){

System.out.println("someGenericParameter : " + someGenericParameter);

}

}

I couldn't find any documents that explain why <T> is required in the above case.

Any thoughts, explanation is appreciated.

[1632 byte] By [appy77a] at [2007-11-27 5:36:12]
# 1
<T> is the declaration of the generic parameter you are using (solely) in the scope of the method. If you do not declare it, the compiler tries finding a Class named T in your package.
stefan.schulza at 2007-7-12 15:06:33 > top of Java-index,Core,Core APIs...
# 2

> <T> is the declaration of the generic parameter you

> are using (solely) in the scope of the method. If you

> do not declare it, the compiler tries finding a Class

> named T in your package.

Thank you stefan for your answer. I was initially confusing the <T> as a return type then I noticed the "void" , so I was a little confused.

So now, from your statement I understand the purpose of prefixing a method with <T>

I also noticed that I could use any character and not just T , for example I could use <B> , and have B in the methods input parameter.

I guess having <T> prefixed to a method signature kind of makes sense because , there could potentially be a class called T defined somewhere else, and by adding <T> to the method you are restricting the method to use the generic type.

I'll give you 5 dukes.

Cheers.

appy77a at 2007-7-12 15:06:33 > top of Java-index,Core,Core APIs...
# 3

You can actually use any sequence of characters for the generic parameter's name. Single capital letters is a convention similar to naming classes, methods, static fields, and so on. Usually, you will find generic parameter definitions at class level rather than method level.

Cheers,

Stefan

stefan.schulza at 2007-7-12 15:06:33 > top of Java-index,Core,Core APIs...