Home >Java >JavaBase >What is the difference between T and ? in java generics?

What is the difference between T and ? in java generics?

王林
王林Original
2020-05-16 09:58:426378browse

What is the difference between T and ? in java generics?

1. T represents an unknown type, used in parameters in methods or generics of classes

(Video tutorial recommendation: java video )

public class ExampleA {
  public <T> void f(T x) {
        System.out.println(x.getClass().getName());
  }
  
  public static void main(String[] args) {
     ExampleA ea = new ExampleA();
     ea.f(" ");
     ea.f(10);
     ea.f(&#39;a&#39;);
     ea.f(ea);
  }
}

2. ? means a general reference in a generic class. It is a placeholder and data cannot be added to the container.

 
// 注意ArrayList中不能加<?>
List<?> list = new ArrayList();
list.add(123);// 错误

Recommended tutorial: java Getting Started with Development

The above is the detailed content of What is the difference between T and ? in java generics?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn