Mixing Generics And Non-Generics Code

If we are work on code that uses generics that is fine and what will happen if we want to mix both generic and non generic code.

Consider below Animal class

also read:

class Animal{
public String toString() {
return "Animal";

if we create the list like below will it compile ???.

List list = new ArrayList<Animal>();

The answer is YES
and using code like this can we get generics behaviour ??.
the answer is NO.
when we use the reference list it is of non-generic version so we will not get any generic behaviour.
so we can add any thing to the list.

List list = new ArrayList<animal>();
list.add(new Object());

and what happens if we pass the above list to a method given below?????.

void iterateAnimalsList(List<animal> list){
for(Animal animal : list){

if we pass the list to the above method it is going to break at run time it will throw class cast exception.

similarly below code also will compile

List<animal>  list = new ArrayList();

Here we can get generic behaviour as reference variable is of generic type.

Note: If we are mixing generic and non-generic versions we will get warning.



About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.