javagenericsbackwards-compatibilityjava-5java1.4

Why does Java claim 1.5 version need to be backward compatible?


Java 1.5 was released with Generics and they wanted it to be backward compatible with earlier versions and hence Java disallowed usage of method specific generics when creating raw instances.

for eg.,

class A<T> {
    <U> U myMethod(U u) {
        return u;
    }
}

If I do ,

A a = new A();

a.myMethod will ask me to pass Object as input and it's return type is Object. Clearly class type parameter 'T' doesn't conflict with myMethod() specific generic which is 'U'. But somehow java said, to handle backward compatability they erase the usage of all generics for raw instances.

The above question is asked multiple times by others and all the answers revolve by saying, because of Backward compatability with earlier versions java disallowed it. [DOT].

But none of the answers provided an instance what could have failed in earlier versions in case java allowed the usage of method specific generics for raw instances.

Can anyone help here by providing one specific instance where the problem would have occured in earlier versions prior to 1.5 if they have allowed it?

Please do not provide any other stackoverflow question's which doesn't have answer related to what could have failed.


Solution

  • Consider a Java program that was written to use Java collection types prior to Java 1.5.

    Prior to Java 1.5, I would write

     List l = new ArrayList();
     l.append("Hello");
     l.append("World");
     String hello = (String) l.get(0);
    

    Now with the type erasure model, I can compile that code in Java 1.5 or later ... without even a compiler warning. But I can also use the exact same collection classes in the modern way; e.g.

     List<String> l = new ArrayList<>();
     l.append("Hello");
     l.append("World");
     String hello = l.get(0);
    

    And note that I am using the same classes and interfaces in both examples.

    Without the erasure model to paper over the cracks, the Java designers would have had to create a parallel set of classes and interfaces for collections; i.e.

    Since the Java type equivalence is based on type names / identity rather than signature-based (or duck typing) equivalence, those two collection hierarchies would be incompatible. That would mean that APIs and implementations that used collections would need to choose between pre-1.5 and post-1.5 collections. Mixing them would be awkward ... and inefficient.

    The end result would have been a big problem for people / organizations who needed to use legacy Java libraries and applications. Basically, migrating to Java 1.5 would have meant a lot of rewriting of applications that worked just fine. That would have killed generics, and Java as an enterprise language.


    We cannot give you specific examples that provably wouldn't work in a Java language where generics were template based and / or there wasn't erasure.