What is T in java?
T is a tag symbol in Java generics, representing Type (Java class).
Java generics (generics) are a new feature introduced in JDK 5. Generics provide a compile-time type safety detection mechanism, which allows programmers to detect illegal types at compile time.
The essence of generics is a parameterized type, which means that the data type being operated is specified as a parameter.
(Related video tutorial sharing: java video tutorial)
The meaning of tags in Java generics:
E - Element (used in collections, because elements are stored in collections)
T - Type (Java class)
K - Key (key)
V - Value (value)
N - Number (numeric type)
? - Represents uncertain java types
S, U, V - 2nd, 3rd, 4th types
Usage examples of generic T in Java:
public class MaximumTest { // 比较三个值并返回最大值 public static <T extends Comparable<T>> T maximum(T x, T y, T z) { T max = x; // 假设x是初始最大值 if ( y.compareTo( max ) > 0 ){ max = y; //y 更大 } if ( z.compareTo( max ) > 0 ){ max = z; // 现在 z 更大 } return max; // 返回最大对象 } public static void main( String args[] ) { System.out.printf( "%d, %d 和 %d 中最大的数为 %d\n\n", 3, 4, 5, maximum( 3, 4, 5 ) ); System.out.printf( "%.1f, %.1f 和 %.1f 中最大的数为 %.1f\n\n", 6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ) ); System.out.printf( "%s, %s 和 %s 中最大的数为 %s\n","pear", "apple", "orange", maximum( "pear", "apple", "orange" ) ); } }
Running results:
3, 4 和 5 中最大的数为 5 6.6, 8.8 和 7.7 中最大的数为 8.8 pear, apple 和 orange 中最大的数为 pear
The above is the detailed content of What is T in java?. For more information, please follow other related articles on the PHP Chinese website!