What is the benefit of having generic constructor for a non-generic class? Java spec permits the following:
class NonGeneric {
<T> NonGeneric() { }
...
NonGeneric ref = new <String> NonGeneric();
}
Can one come up with a realistic example of when it enhances the typesafety of the class? How would it be better than using Generic in the first place.
I understand that Java designers wanted the constructors to be more consistent with methods. Given that constructors can have side-effects, generic constructors can use generics to mutate some parameters whose references aren't retained, as in
<T> NonGeneric(T obj, List<T> list) {
list.add(obj);
// Don't hold a reference to list
}
The only use that I can think of would be if the constructor needed to use a generic object while it was running, but did not store that object once it was complete.
For example:
<T> NonGeneric(T[] blank, List<T> list) {
// Sort that list
T[] array = list.toArray(blank);
Arrays.sort(array);
// Pull out the values as strings
this.list = new ArrayList<String>(array.length);
for (T value : array) {
this.list.add(value.toString());
}
}
It is most likely just something that the language designers decided to do just in case somebody wanted it, since there was no reason to prevent people from doing it.
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