wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Generics and casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Generics and casting" Watch "Generics and casting" New topic
Author

Generics and casting

Anup Om
Ranch Hand

Joined: Dec 30, 2009
Posts: 62


When I compile and run this code, it works. I can even print i.elementData(). I don't understand why the cast in elementData() method is not throwing an exception?

How does casting work with generics?


SCJP6
Ireneusz Kordal
Ranch Hand

Joined: Jun 21, 2008
Posts: 423
Anoo Kota wrote: I don't understand why the cast in elementData() method is not throwing an exception?

Because you don't use returned object, you simply lose it.
Change line 15 to:

and it will throw exception.
Type checking occurs when object is assigned to another variable or is used in the expression that expects that this object is of declared type.
Anup Om
Ranch Hand

Joined: Dec 30, 2009
Posts: 62

Type checking occurs when object is assigned to another variable or is used in the expression that expects that this object is of declared type.


But why is the cast in elementData() method not failing? x is a String and E is determined to be a Integer. Casting a String to Integer should cause an exception.
What am I missing here?
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18650
    
    8

Your type parameter E doesn't have a specified upper bound, so at run time it can represent any kind of object. So the compiler converts ("erases" is the technical term) the type parameter E to its upper bound, which is Object.

Now your cast is to Object, which can't possibly fail. But as Ireneusz pointed out, assigning the result of the cast to an integer would certainly fail.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Generics and casting