Skip to main content
3 of 5
Added clarification
PM 77-1
  • 597
  • 2
  • 11
  • 24

Instantiating a run-time implementation of an interface

Below is my code that was written for the following task (based on an SO question):

Given a Java Collection (of N elements) create an ArrayList, containing N collections of the same type with just one element in each.

Here's my code for such method:

public static <E> ArrayList<Collection<E>> SplitCollection (Collection<E> col) throws InstantiationException, IllegalAccessException {
    ArrayList<Collection<E>> listOfCollections = new ArrayList<>();
    for(E el: col) {
        // creating an empty collection of type E
        Collection<E> colEl = col.getClass().newInstance();
        colEl.add(el);
        listOfCollections.add(colEl);
    }
    return listOfCollections;
}
  1. Is there a better way to create a run-time instance of an implementation class for an interface?
  2. Did I overdo anything in light of type erasure?
  3. Other code critique?

Added clarification (07/24/2014):

When I decided to use no-argument constructor I was aware that the very existence of one is not (and cannot be) enforced by the interface. As it stated in the docs:

All general-purpose Collection implementation classes (which typically implement Collection indirectly through one of its subinterfaces) should provide two "standard" constructors: a void (no arguments) constructor, which creates an empty collection, and a constructor with a single argument of type Collection, which creates a new collection with the same elements as its argument. In effect, the latter constructor allows the user to copy any collection, producing an equivalent collection of the desired implementation type. There is no way to enforce this convention (as interfaces cannot contain constructors) but all of the general-purpose Collection implementations in the Java platform libraries comply.

So I was writing my code for general-purpose Collection implementations.

I never intended this code to be used for production purposes. I merely wanted to see how far programming to interface together with Generics could get you before you have to use a concrete type and implementation.

PM 77-1
  • 597
  • 2
  • 11
  • 24