Generic Methods
本文最后更新于 2024年3月19日 上午
Generic methods are methods that introduce their own type parameters. This is similar to declaring a generic type, but the type parameter’s scope is limited to the method where it is declared. Static and non-static generic methods are allowed, as well as generic class constructors.
The syntax for a generic method includes a list of type parameters, inside angle brackets, which appears before the method’s return type. For static generic methods, the type parameter section must appear before the method’s return type.
The Util class includes a generic method, compare, which compares two Pair
objects:
1 |
|
The complete syntax for invoking this method would be:
1 |
|
The type has been explicitly provided, as shown in bold. Generally, this can be left out and the compiler will infer the type that is needed:
1 |
|
This feature, known as type inference(类型推断), allows you to invoke a generic method as an ordinary method, without specifying a type between angle brackets.