What is the difference between:
public <T> void createArray(T sample){
ArrayList<T> list = new ArrayList<T>();
list.add(sample);
}
and
public void createArray(T sample){
ArrayList<T> list = new ArrayList<T>();
list.add(sample);
}
I read that the method signature for using types should have <T>
before the return type but how come I am still able to create the method without the <T>
? What is the implication if I do or do not put it?
(Yes, this is legal code; see Java Generics: Generic type defined as return type only.) The return type will be inferred from the caller. However, note the @SuppressWarnings annotation: that tells you that this code isn't typesafe. You have to verify it yourself, or you could get ClassCastExceptions at runtime.
In other words, the T is an actual part of the syntax for Generics and it means that the paramter for the Class can be of variable type? <T> is the generic type. Maybe read the official tutorial. Yes, the angle-brackets with one (or more) types is the syntax for generics.
< 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. WHAT DOES GENERIC MEAN? Generic is a way to parameterize a class, method, or interface.
Well there's no difference between the first two - they're just using different names for the type parameter ( E or T ). The third isn't a valid declaration - ? is used as a wildcard which is used when providing a type argument, e.g. List<?>
In the second method, the type parameter would be typically defined in the class declaration to which the method belongs:
class MyClass<T> {
public void createArray(T sample){
ArrayList<T> list = new ArrayList<T>();
list.add(sample);
}
...
}
So the second method belongs to a generic type. The first method is a generic method because it defines its own type parameter.
In the first case, the generic parameter T
is defined for the method. Other methods may have a different T
.
In the second case, the generic parameter T
is defined for the class or interface. All methods within that class or interface must have the same T
.
Defining a class-wide generic allows you to enforce the same type parameter on many methods. You can also have fields of the generic type. See ArrayList<t>
for an example.
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