• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

RawType and ClassCastException

 
Aniket Patil
Ranch Hand
Posts: 218
  • Mark post as helpful
  • send pies
  • 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 ]
 
wise owen
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
for-each loop uses "Iterator<Integer> iterator()" in your case.
 
Tiffiny Yang
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
  • 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
  • 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)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic