views:

284

answers:

1

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
}
+4  A: 

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.

Jonathan
Yeah, it allows generic methods to be replace by constructors (but why would you want to?). I've never actually seen one in the wild. For my money, it's a complication that the language could have done without (as C# did later when it introduced its version of Java generics).
Tom Hawtin - tackline