• Post Reply Bookmark Topic Watch Topic
  • New Topic

Generic Casting  RSS feed

 
Ryan Hendrixson
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I came across the following code in my SCJP 6 book, and it confuses me:

Node<Number> numNode = new Node<Number>(20);
Node<?> anyNode = numNode;
Node<String> strNode = (Node<String>) anyNode; //Unchecked cast warning
strNode.setData("Peekaboo"); //No Exception
Number num = numNode.getData(); //Exception

Why is there no exception, runtime or compiletime, at the fourth line where strNode is set? Isn't strNode still referencing an object of type Node<Number>? The code definitely compiles and runs up to the fourth line, but I just can't wrap my head around this one, and the book doesn't really explain it too well. Any takers? (I'm hoping this is more simple than I'm making it out to be)
 
Stephan van Hulst
Saloon Keeper
Posts: 7987
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ryan, welcome to CodeRanch.

Your question is impossible to answer without knowing what the setData() and getData() methods look like. Kindly post their signatures, or preferably the entire Node class.
 
Ryan Hendrixson
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
good point:

class Node<E>{
private E node;
Node(){}
Node(E e){this.node = e;}
public void set(E e){this.node = e;}
public E get(){return this.node;}
}
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ryan Hendrixson wrote:I came across the following code in my SCJP 6 book, and it confuses me:

Node<Number> numNode = new Node<Number>(20);
Node<?> anyNode = numNode;
Node<String> strNode = (Node<String>) anyNode; //Unchecked cast warning
strNode.setData("Peekaboo"); //No Exception
Number num = numNode.getData(); //Exception

Why is there no exception, runtime or compiletime, at the fourth line where strNode is set?


No compiler error because strNode is declared to be of type Node<String>. No error at runtime because generics (mostly) don't exist at runtime--it's just a Node with a setData(Object) method.
 
Ryan Hendrixson
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That REALLY made it just click for me. Thank you so much!
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're quite welcome!

And welcome to the Ranch!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!