• 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

RawType and ClassCastException

 
Ranch Hand
Posts: 218
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
import java.util.*;

class RawType
{
public static void main(String[ ] args)
{
List<Integer> l = new ArrayList<Integer>( );
insert(l);
Object o = l.get(0); <---This works
System.out.println(o);
for(Object s :l ) <--- This doesen't work, exception thrown, why?
System.out.println(s);
}

static void insert(List l1)
{
l1.add(new Float(12.3));

}
}

I am trying to store a List<Integer> refernce in an Object using the modified for loop. When the "get( )" method is used, it correctly stores a Float in Object. However, in the modified for loop, it throws a ClassCast Exception. Why does it work for the get( ) method and not in the second case?
[ May 17, 2006: Message edited by: Aniket Patil ]
 
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
for-each loop uses "Iterator<Integer> iterator()" in your case.
 
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Aniket

I tried you code, it works , no run-time excetption thrown.
 
Aniket Patil
Ranch Hand
Posts: 218
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Owen, many thanks for that link. It cleared my doubt.

Tiffany, i am using JDK 1.5.06 and the code still throws an exception. The reason being an Iterator<Integer> is used by the enhanced-for loop, which expects to find and retrieve Integer objects in the list.

However, the iterator encounters a Float in the list, and it has no hope of being able to convert a Float into an Integer due to which it fails to do its job of retrieval. Hence a ClassCastException is thrown as follows:
java RawType
12.3
Exception in thread "main" java.lang.ClassCastException: java.lang.Float
at RawType.main(RawType.java:11)
 
reply
    Bookmark Topic Watch Topic
  • New Topic