简体   繁体   中英

Java Generics - How is a raw type different from a non generic type

In java generics context, a raw type is a non-parameterized invocation of a generic type. They also say that any non-generic type is not a raw type.

My confusion is, why they say that non-generic type is not a raw type? How is it different from a non-parameterized invocation of a generic type. Consider the following 2 cases.

Case 1:

class A<T>{

}
A a = new A(); //Raw type

Case 2:

class A{

}
A a = new A();//Non-generic type

If variable "a" behaves identically in both cases, why do they say case[1] is raw type while case[2] is not?

The concept of raw type is only relevant to generic types due to the issue that the raw type is considered to be assignment-compatible with the generic type, but doing such assignment opens a loophole in type safety otherwise guaranteed for the generic type. For example, consider a method void workWith(A<Integer> a) . You will be allowed to pass in your a variable, resulting in a type safety incident.

As non-generic types cannot suffer from such issues, they are not termed "raw types".

As said in JLS :

A non-generic class or interface type is not a raw type.

You can feel the difference in the syntactic level :

if we have parameterized class:

class A<X> {
   class B<Y> {
      Y y;
   }
}

then just A name type or B name type aren't non-generic types, they are raw types, and this influences on how you can access to them:

all this constructions will cause compile time error:

A<Integer>.B ab = null;
A.B<Integer> ab = null;

Raw type has to do with the bounding of generic types and type erasure. If you have ArrayList<? extends Shape> ArrayList<? extends Shape> then the bound type is Shape and will be the raw type at compile time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM