I\'m starting to learn Genericsfor Java and I read several tutorials, but I\'m a bit confused and not sure how a generic method is declared.
The problem is that your code is using the same character A, but it has several different "meanings" in the different places:
public class Box {
braces required, because you are saying here: Box uses a generic type, called T.
Usages of T go without braces:
private T a;
public void setA(T a) {
But then
public List transform(List in) {
is introducing another type parameter. I named it T2 to make it clear that it is not the same as T. The idea is that the scope of T2 is only that one method transform. Other methods do not know about T2!
public static A getFirstElement(List list) {
Same as above - would be "T3" here ;-)
EDIT to your comment: you can't have a static method use the class-wide type T. That is simply not possible! See here for why that is!
EDIT no.2: the generic allows you to write code that is generic (as it can deal with different classes); but still given you compile-time safety. Example:
Box stringBox = new Box<>();
Box integerBox = new Box<>();
integerBox.add("string"); // gives a COMPILER error!
Before people had generics, they could only deal with Object all over the place; and manual casting.