5

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?

  • Behaviorally it's basically the same. Semantically it's pretty different. – Oliver Charlesworth Mar 26 '15 at 09:50
  • You can read http://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it – Ortomala Lokni Mar 26 '15 at 09:53
  • @Ortomala Lokni thanks for that link. It says "Essentially, raw types behaves just like they were before generics were introduced" which probably tells me that my variable "a" will behave exactly the same in both cases. If that is right, please answer this question. I will accept it. But I still wonder in that case why they say that a non-generic one is NOT A RAW TYPE? What is wrong in saying that all non-generic types also are RAW TYPE? –  Mar 26 '15 at 10:24
  • A good resource with lots of details on generics: [Java Generics FAQ](http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html) – Jesper Mar 26 '15 at 10:58

3 Answers3

3

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".

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • @SureshKumarKV: Well, use of raw types gives you a warning, whereas use of non-generic types do not. – newacct Mar 26 '15 at 20:16
1

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;
Andremoniy
  • 34,031
  • 20
  • 135
  • 241
  • I agree. I am more interested to know if the variable "a" behaves different in the 2 cases I have given. –  Mar 26 '15 at 10:22
0

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

Cory
  • 11
  • 2