Java generic method declaration fundamentals

前端 未结 3 762
慢半拍i
慢半拍i 2021-01-14 09:36

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.

<
相关标签:
3条回答
  • 2021-01-14 10:05

    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) {
        }
    }
    
    0 讨论(0)
  • 2021-01-14 10:07

    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.

    0 讨论(0)
  • 2021-01-14 10:22

    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

    0 讨论(0)
提交回复
热议问题