问题
I was reading and reviewing the following site and had a question.
https://www.geeksforgeeks.org/angle-bracket-in-java-with-examples/
In the explanations below they show class definitions followed by <T>
and then when actually implementing these classes they use different types such as or as the parameters. My question is: is the '' notation actually a defined syntax in Java? In particular, is the T a necessary thing in order to define a "Generic"? And then does it basically mean that the parameters can be of multiple different types? Also, if anyone can reword or explain in simpler terms what the meaning of a generic is that would be very helpful. Thanks.
回答1:
The <T>
is indeed a syntax defined by Java, but you can use whatever name you want to name a type, you don't need to use T
, for example this is valid:
public class Box<MyType> {
private MyType t;
public void set(MyType t) { this.t = t; }
public MyType get() { return t; }
}
But, stick with T
or other common type names, as other people are already used to seeing those as the "generic types" so it makes reading your code simpler.
I recommend you read Java's Trail about Generics, where you can find the most commonly used type parameter names:
E - Element
K - Key
N - Number
T - Type
V - Value
S,U,V etc. - 2nd, 3rd, 4th types
As for "what the meaning of generics is", check this other page.
回答2:
It’s defined syntax since Java 5. You need a type parameter (one or more) for defining a generic. The type parameter needs not be called T
, any Java identifier will do. A single uppercase letter is conventional, and T
for type is what we often pick if we haven’t got a specific reason for some other letter.
The actual type parameter has to be a reference type. Values still always go into actual parameters in round brackets, not into type parameters (unlike in C++, for example). You can make a new ArrayList<Integer>(50)
, a list of Integer
objects with an initial capacity for 50 of them.
That the actual type parameter has to be a reference type means that you can have a List<String>
, a List<LocalDate>
or a list of an interface type that you have declared yourself, even a List<int[]>
. In the Java versions I have used (up to Java 10) the type parameter cannot be a primitive type (like int
), but it can be an array type (like int[]
or String[][]
, though often impractical). Allowing primitive types may come in a future Java version.
Link: Similar question: What does < T > (angle brackets) mean in Java?
来源:https://stackoverflow.com/questions/60200188/java-generics-t-meaning