Because I recently looked at generics and saw some reflection, I had doubts about object, T (the following generic type), or.
Let's try to understand the object class, learn Java should know that object is the parent class of all classes, note: then this means that it is a very wide range! first of all remember this, if your parameter type is object, then the parameter type will be very wide!
"Thinking in Java" has many reasons for the emergence of generics, one of the most compelling reasons is to create container classes. How does this come to be understood? My understanding is that this can be done in order to create the container class, but to return to the generic to define a certain type of form.
So now we can summarize the important two-point difference between object and T is:
- The object range is very wide, and T qualifies the type from the beginning (including it can qualify type Object).
- Object because it is the parent class of all classes, it enforces the type conversion, and T restricts the type conversion by restricting a specific type from the beginning when coding (note that the code is being written). (The reason to emphasize that when writing code is because generics in the virtual machine will be erased by the JVM of its specific type information, this can refer to generics, here do not extend).
For example, the list class in the JDK is a generic class. Now we make it the type is object.
New Arraylist<object>(); int i = 0; = "S"; List.add (i); List.add (s);
The list itself is a generic class, and now we specify that it receives parameters of type object, where it is possible to put any type of argument in it, and in the case of it it is necessary to cast the type into a specific type.
Now if we specify the list to receive a string type of argument, then the list can only be placed in string type, and when it is removed, it is not forced type conversion.
This brings us to the revelation that when writing a similar list class, it is important to note whether generics are used. Be sure to write a few more generic classes, talk more about understanding, or you may be stirred together.
And then, this might be used when the reflection needs to get the class type, and it's interpreted as receiving an indeterminate type, a bit like an object. I have an understanding of it that if only "?" is used. Then it's the same as object, but "?" There is a little bit more "advanced" than the use of object, that is, it can narrow an indeterminate range, using a similar "? Extends test, which means that only the inherited class receiving the test class is received, is it smaller than the range of object?
The above is the difference between object, T, and. Write a few more lines of code, do more experiments, more discussion, you know when and where the appropriate use.
Object, T (generic),? difference in Java