I found that you can call a generic method with a special Type, e.g.:
suppose we have a generic method:
class ListUtils {
public static <T> List<T> createList() {
return new ArrayList<T>();
}
}
we can call it like:
List<Integer> intList = ListUtils.<Integer>createList();
But how can we call it when it's statically imported? e.g.:
List<Integer> intList = <Integer>createList();
this does not work.
Static and non-static generic methods are allowed, as well as generic class constructors. The syntax for a generic method includes a list of type parameters, inside angle brackets, which appears before the method's return type.
To call a generic method, you need to provide types that will be used during the method invocation. Those types can be passed as an instance of NType objects initialized with particular . NET types.
A generic class and a generic method can handle any type of data.
Cannot Instantiate Generic Types with Primitive Types. Cannot Create Instances of Type Parameters. Cannot Declare Static Fields Whose Types are Type Parameters. Cannot Use Casts or instanceof With Parameterized Types.
You can't. You'd have to reference it using the class name.
It seems that having:
void foo(List<String> a) {}
and calling foo(createList())
does not infer the correct type. So you should either explicitly use the class name, like ListUtils.createList()
or use an intermediate variable:
List<String> fooList = createList();
foo(fooList);
Finally, guava has Lists.newArrayList()
, so you'd better reuse that.
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