Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benefit of Generic Constructors

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
}
like image 546
notnoop Avatar asked Aug 19 '09 13:08

notnoop


1 Answers

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.

like image 107
Jonathan Avatar answered Oct 21 '22 11:10

Jonathan