Generics erasure and legacy code

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?

Answer

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;
}

Leave a Reply

Your email address will not be published. Required fields are marked *