Below is my code that was written for the following task (based on an SO question):
Given a Java
Collection
(of N elements) create anArrayList
, 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;
}
- Is there a better way to create a run-time instance of an implementation class for an interface?
- Did I overdo anything in light of type erasure?
- Other code critique?
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 implementCollection
indirectly through one of its subinterfaces) should provide two "standard" constructors: a void (no arguments) constructor, which creates an emptycollection
, and a constructor with a single argument of typeCollection
, 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-purposeCollection
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.