Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics and casting

 
Anup Om
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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?
 
Ireneusz Kordal
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Sheriff
Posts: 21107
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic