I stumbled upon a function looking like this:
public void function(Class<?> clazz) {...}
What are the pros/cons of changing the method to:
public <T> void function(Class<T> clazz) {...}
edit: what are the compile time / runtime diff.
< T > is a conventional letter that stands for "Type", and it refers to the concept of Generics in Java. You can use any letter, but you'll see that 'T' is widely preferred.
Well there's no difference between the first two - they're just using different names for the type parameter ( E or T ).
? is a wildcard and means any subclass of ONEITEMInterface including itself. T is a specific implementation of ONEITEMInterface in this case.
What Does Class Mean? A class — in the context of Java — is a template used to create objects and to define object data types and methods. Classes are categories, and objects are items within each category. All class objects should have the basic class properties.
todd.run is totally right on, but that's only half the answer. There are also use cases for choosing <T>
over <?>
(or vice versa) that apply when you don't add type parameter to the class that encloses the method. For example, consider the difference between
public <E extends JLabel> boolean add(List<E> j) {
boolean t = true;
for (JLabel b : j) {
if (b instanceof JLabel) {
t = t && labels.add(b);
}
}
return t;
}
and
public boolean add(List<? extends JLabel> j) {
boolean t = true;
for (JLabel b : j) {
if (b instanceof JLabel) {
t = t && labels.add(b);
}
}
return t;
}
The first method will actually not compile UNLESS you add an appropriate type parameter to the enclosing class, whereas the second method WILL compile regardless of whether the enclosing class has a type parameter. If you do not use <?>
, then you are locally responsible for telling the compiler how to acquire the type that will be filled in by the letter used in its place. You frequently encounter this problem - needing to use ? rather than T - when attempting to write generic methods that use or need "extends" and "super." A better but more elaborate treatment of this issue is on page 18 of Gilad Bracha's Generics Tutorial (PDF). Also see this stack overflow question whose answer illuminates these issues.
Check out this stack overflow link for information about your second question: Java generics - type erasure - when and what happens. While I don't know the answer to your question about the compile time difference between <?>
and <T>
, I'm pretty sure the answer can be found at this FAQ that erickson mentioned in that post.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With