I'm looking for a way to allow the constructor of this class take in an array of a generic type.
public class my
{
public my(T[] arr) // how resolve this
{
...
}
}
There are two ways for you to have a type array as a parameter in your constructor. One, you can add the parameter to the class like so...
public class my<T> {
public my(T[] arr)
{
...
}
}
Or, your constructor can take in a Type Parameter, like so:
public class my {
public <T> my(T[] arr)
{
...
}
}
You can initialize an object of the first class like so:
my<SomeClass> varName = new my<>(arrayOfSomeClass);
And you can initialize an object of the second class like so:
my varName = new <SomeClass>my();
Hope this helps!
I can't think of any situation where I would want a generic constructor in a non-generic class. But hey, here you go:
You just add <T> to the constructor declaration:
public <T> my(T[] arr) {
}
Be careful when you call this constructor. Because it is generic, you can't use primitive types like int or char. You need to use their reference type counterparts, Integer and Character.
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