Java generic method declaration fundamentals

一笑奈何 提交于 2019-12-01 09:09:37

问题


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;
    }

回答1:


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.




回答2:


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) {
    }
}



回答3:


If you have a requirement in your method where you need to return type is depends on your method parameter at that time you can write angle bracket before method signature as shown in your example, In short, as word suggest Generic is used for feature where same class or utility required to be used for multiple type of objects



来源:https://stackoverflow.com/questions/39487877/java-generic-method-declaration-fundamentals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!