The fact that a raw type of generic class can take all different variations of that generic class is matter of Java compatibility?

StackOverflow https://stackoverflow.com/questions/11403830

문제

I noticed that a raw type of a generic class can take(point to) all different variations of the generic class and also all different variations of a generic class can take(point to) the raw type of the generic class. Why Java Generics behaves like that? Is it purely because of compatibility with the old versions of Java?

Example:

//Main.java
public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) {

    List listRaw = new ArrayList();
    List<Student> listQualified = new ArrayList<Student>();
    List<?> listUnbounded = new ArrayList<Student>();
    List<? extends Student> listUpBounded = new ArrayList<Student>();
    List<? super Student> listDownBounded = new ArrayList<Student>();

    // List raw type can take all different variations of List
    List rawList1 = listRaw;
    List rawList2 = listQualified;
    List rawList3 = listUnbounded;
    List rawList4 = listUpBounded;
    List rawList5 = listDownBounded;

    // All different variations of List can take List raw type
    listRaw = rawList1;
    listQualified = rawList2;
    listUnbounded = rawList3;
    listUpBounded = rawList4;
    listDownBounded = rawList5;

    }

}

//People.java
public class People {

    public static class Student extends People {
    }

    public class HistoryStudent extends Student {
    }

    public class MathStudent extends Student {
    }
}
도움이 되었습니까?

해결책

One of the main challenges the Sun engineers faced was to maintain the backward compatibility. For example, if you are not able to assign:

List list = new ArrayList<Student>();

then, you wouldn't be able to use older library methods. i.e.:

List org.apache.commons.collections.ListUtils.intersection(List arg0, List arg1)

Also remember those types dissapear on runtime as described on http://docs.oracle.com/javase/tutorial/java/generics/erasure.html

다른 팁

Yes. Actually generics were added in java 5,and the language had to mantain the runtime compatibility with older releases. This compromise works because actually generics info disappear once the code is compiled (type ereasure) into a .class, even if you can have infoby reflection wheter some methods accept generic type parameters. If you compile code similar to what you wrote it works fine, but normally the compiler would warn you that you are using 'raw' types.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top