Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generic method declaration fundamentals

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.

When I use a generic type, what is the correct order to define the method? I found this sample, when do I need to use the angle brackets and when not?

public class Box<A> {

    private A a;
    ...

    public void setA(A a) {
        this.a = a;
    }

    public <A> List<A> transform(List<A> in) {
        return null;
    }

    public static <A> A getFirstElement(List<A> list) {
        return null;
    }

    public A getA() {
        return a;
    }
like image 914
Eve Avatar asked Jun 24 '26 18:06

Eve


2 Answers

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<T> { 

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 <T2> List<T2> transform(List<T2> 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> A getFirstElement(List<A> 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<String> stringBox = new Box<>();
 Box<Integer> 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.

like image 134
GhostCat Avatar answered Jun 26 '26 11:06

GhostCat


Your example shows two different concepts: generic classes and generic methods

This is a generic class introducing a type parameter <A>:

public class Box<A> {

}

While these are generic methods introducing their own type parameter <A>:

public <A> List<A> transform(List<A> in) {
    return null;
}

public static <A> A getFirstElement(List<A> list) {
    return null;
}

Compare it with a class having a field of a specific name and a method having a parameter of that name:

public class Box {
    private String name;

    publix Box(String name) {
    }
}
like image 28
Michaela Maura Elschner Avatar answered Jun 26 '26 09:06

Michaela Maura Elschner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!