JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

Mixing Generics And Non-Generics Code

September 18, 2008 by Krishna Srinivasan Leave a Comment

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:

  • New Features in Java 5.0
  • Generics in Java 5.0
  • Annotations in Java 5.0

[code lang=”java”]
class Animal{
public String toString() {
return "Animal";
}
}
[/code]

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

[code lang=”java”]
List list = new ArrayList<Animal>();
[/code]

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.

[code lang=”java”]
List list = new ArrayList<animal>();
list.add(new Object());
list.add("rere");
list.add(1);
[/code]

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

[code lang=”java”]
void iterateAnimalsList(List<animal> list){
for(Animal animal : list){
System.out.println(animal);
}
}
[/code]

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

[code lang=”java”]
List<animal> list = new ArrayList();
[/code]

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.

Filed Under: Java Tagged With: Java 5.0

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.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved