File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Generic--- ClassCastException Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Generic--- ClassCastException" Watch "Generic--- ClassCastException" New topic

Generic--- ClassCastException

Lucky J Verma
Ranch Hand

Joined: Apr 11, 2007
Posts: 278
I am modifying the generic based list in some nongeneric lagecy code.
In legacy code, the method is inserting WRONG data ,into Integer List.
It compiles(with warning) & runs with ClassCastException.

But K&B Book ,chap 7,pg 577 ,says "code compiles & runs .No Run time Exception".
Please let me know ,if my output is correct.or if its possible,though not safe,,to insert String(nongenerics code) in Integer List(for generic code)

My code is

import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;

//code ot mix legacy code with generic code

//-----legacy code-----
class Adder{

void insert(List list) //modfyng new list
list.add("string adding to Integer List");

int addAll(List list)
Iterator it=list.iterator();
int total=0;
int i=((Integer);
//String i=(String);

}return total;
//------------------------Generics code --------
public class GenericsDemo4 {
public static void main(String args[])
{List<Integer> mylist=new ArrayList<Integer>();

Adder adder=new Adder();


System.out.println("no of element "+adder.addAll(mylist));

Suman Sharma
Ranch Hand

Joined: May 16, 2005
Posts: 72
In GenericsDemo class, a list of Integers has been created, and it is passed to insert method of the non-generic class (Adder). Here list is declared of raw type.
The raw list can accept data of different type such as String. But it creates problem when we retrieve data from the raw list type. It outputs the integers, and then gives ClassCastException when it tries to retrieve the String data.
wood burning stoves
subject: Generic--- ClassCastException
It's not a secret anymore!