• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Generic--- ClassCastException

 
Ranch Hand
Posts: 278
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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;
while(it.hasNext())
{
int i=((Integer)it.next());
//String i=(String)it.next();

System.out.println(i);
total=total+1;
}return total;
}
}
//------------------------Generics code --------
public class GenericsDemo4 {
public static void main(String args[])
{List<Integer> mylist=new ArrayList<Integer>();
mylist.add(9);
mylist.add(22);
mylist.add(23);

Adder adder=new Adder();

adder.insert(mylist);
System.out.println(mylist);

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




}
}
 
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic