Generics surely is a neat thing in Java 5.0, allowing us to have out-of-the-box type-safe collections, but while using this feature some questions may appear, like the how to use downcasting.
Suppose you have this:
MyBase a1 = new MyImpl();
MyBase a2 = new MyImpl();
List<MyBase> list = new ArrayList<MyBase>();
list.add(a1);
list.add(a2);
And, for some unknown reason, want to do this:
MyImpl[] array = null;
array = list.toArray(array);
Or this:
List<MyImpl> anotherList = list;
Or even this:
List<MyImpl> anotherList = (List<MyImpl>)list;
What happens?
Well, in the first case everything goes well, the elements copied to the array and correctly downcasted to the array’s type, just as long as MyImpl really is a subtype of MyInterface, if not you’ll get a nasty ArrayStoreException.
In the second and third cases you’ll always get an error in compile time, the List<MyImpl>and List<MyBase> are seen as two completely different types by the compiler so there’s no way to convert one into the other, even if MyBase is a supertype of MyImpl. One workaround is having a helper class that copies one collection into the other.
Technorati Tags: Generics