Home  >  Q&A  >  body text

What is the difference between <T> T and T in java?

Why is an error reported? Isn’t first the T type? And <T> What is the difference between T and T?

伊谢尔伦伊谢尔伦2712 days ago687

reply all(3)I'll reply

  • 高洛峰

    高洛峰2017-05-17 10:09:21

    If you wish getMax 方法的返回值类型为 T,就要这样去定义getMaxMethod:

    public T getMax()

    If you want the type of return value of the getMax method to be determined by the caller, then define the getMax method like this:

    public <A> A getMax() {
        //...
        return (A)result;
    }

    The A here must not be the same letter as the T declared in the class name.

    In short, the T and <T> T you mentioned are fundamentally two different uses.

    reply
    0
  • P粉504247697

    Hello teacher, I would like to ask why A must not be the same letter as T? I tried it and it works.

    P粉504247697 · 2022-08-30 01:01:47
  • 阿神

    阿神2017-05-17 10:09:21

    You should remove the second <T>.
    <T> is to define generics and T is to use generics
    You need to understand generic classes and generic methods

    The <T> on the reason class and the <T> on the method should not appear repeatedly, otherwise it will be considered that the generic type has been redefined on the method.

    reply
    0
  • Cancelreply