Programming, Java
It used to be that if a method returned Object, you had to cast it to the appropriate class.
public void doStuff(Collection pCollection) {
String[] array = (String[]) pCollection.toArray(new String[pCollection.size()]);
}You couldn't do the following:
public void doStuff(Collection pCollection) {
String[] array = pCollection.toArray();
}Because toArray() didn't know to return the appropriate class.
With Java 1.5, generics and dynamic proxies allow you to do some magic.
public void doStuff(CollectionpCollection) { BetterCollection betterCollection = BetterCollectionFactory.asBetterCollection( pCollection, String.class); String[] array = betterCollection.toArray(); }
The article doesn't cover everything, like whether the covariant return type can be brought through methods:
public void callMethod(CollectionpCollection) { BetterCollection betterCollection = BetterCollectionFactory.asBetterCollection( pCollection, String.class); doStuff(betterCollection); } public void doStuff(Collection pCollection) { // No casting, but perhaps the instance will take care of it? String[] array = pCollection.toArray(); }
Or whether it's possible to get rid of the explicit String.class param:
public void doStuff(CollectionpCollection) { // Get the class of pCollection through introspection and determine the element type as String.class BetterCollection betterCollection = BetterCollectionFactory.asBetterCollection( pCollection); String[] array = betterCollection.toArray(); }
This flexibility appeals the hardcore geek in me, but I still have doubts about using it in a project. Is the type still checked at compile time? Is it possible to run into ClassCastException using this method? Is it possible to run into subtle type bugs using this method?
But still. Very cool.
String[] array = collection.toArray()
doesn't work. not the Collection in JDK.
see
http://www.jroller.com/page/javay/20040806#list_toarray_in_1_5
even if it works, I don't think you should call it 'covariant'