In many books is said that the reason for which Java's generic use erasure is to have compatibility with legacy code.
Ok, very good but can anyone show me some simple examples where some generic code interact with old legacy code and vice-versa?
In many books is said that the reason for which Java's generic use erasure is to have compatibility with legacy code.
Ok, very good but can anyone show me some simple examples where some generic code interact with old legacy code and vice-versa?
Having compatibility with the legacy code means that it should be able to run on the new version of JVM without compilation. Let's say you are having some legacy library without source code. This ensures that you'll be able to run it on Java 5. Your new code will be able to call legacy code without problems.
Here's an example that wouldn't be possible without type erasure:
public static void main(String[] args) {
List<String> newList = legacyMethod();
for (String s : newList) {
System.out.println(s);
}
}
public static List legacyMethod() {
List oldList = new ArrayList();
oldList.add("a");
oldList.add("b");
oldList.add("c");
return oldList;
}
Run old code on a current JRE and the uses of the likes of List
will be old code using new. Methods suck as Collections.sort
will be new code calling back to old.
Take any old Java library which hasn't been ported to Java 5, yet. You'll find plenty of places where the old code returns or accepts List
. Without erasure, you couldn't use generics in your code (to make your life more simple) and pass your lists as parameters to the framework without (shallow) copying the whole thing - List
and List<String>
would be as different as String
and File
.
In a similar fashion, when the library returns a list, you'd either have to use the pre-5 syntax with an iterator to process it or copy the basic list into a generified one.
There would be way to work around that. Sun could have made List
equal to List<Object>
or, God forbid, List<?>
. But that would have introduced even more subtle problems. So they decided to go the way of least resistance and use the generic information (mostly) during compilation.