Email address:
SCJP/OCPJP 1.6 certification
Practice Exams and Training
Java Generics Explained » Discussions

Mixing raw and generic types

Approximately at 22:44 you say that - given

Cage<Cat> catsCage = new Cage<Cat>();

- "if we miss to add the actual parameter at one side it will compile but we will get a compiler warning".

Well, what I understood is that mixing raw and generic types bring to different behavior:

1) we get a compiler warning when assigning a raw type to a parameterized type. Ex:

Cage<Cat> catsCage = new Cage();  //compiler warning unchecked conversion

2) we don't get a compiler warning when assigning a parameterized type to a raw type but in this situation we lose type information. Ex:

   Cage catsCage = new Cage<Cat>();  //compiles fine
   catsCage.setAnimal(new Cat());    //we get a compiler warning because the variable catsCage of raw type Cage does not have access to the generic type information
   Cat aCat = catsCage.getAnimal();  // compilation error

Is this correct?


Very correct!

What all you need to know about warnings is adding a non-generic object to a generic reference will give you a warning.

I'd provide you with an example code, but you seem to have already provided it yourself :-)


ExamLab © 2008 - 2024