File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes RawType and ClassCastException Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "RawType and ClassCastException" Watch "RawType and ClassCastException" New topic
Author

RawType and ClassCastException

Aniket Patil
Ranch Hand

Joined: May 02, 2006
Posts: 218
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 ]

SCJP 5.0 | SCWCD 1.4 <br /> <br />If you don't know where you are going, any road will take you there!
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
for-each loop uses "Iterator<Integer> iterator()" in your case.
Tiffiny Yang
Ranch Hand

Joined: Mar 29, 2006
Posts: 124
Aniket

I tried you code, it works , no run-time excetption thrown.
Aniket Patil
Ranch Hand

Joined: May 02, 2006
Posts: 218
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)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: RawType and ClassCastException