File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Generic Casting Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Generic Casting" Watch "Generic Casting" New topic
Author

Generic Casting

Ryan Hendrixson
Greenhorn

Joined: Feb 09, 2012
Posts: 3
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
Bartender

Joined: Sep 20, 2010
Posts: 2771

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

Joined: Feb 09, 2012
Posts: 3
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

Joined: Jan 03, 2004
Posts: 3143
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

Joined: Feb 09, 2012
Posts: 3
That REALLY made it just click for me. Thank you so much!
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 3143
You're quite welcome!

And welcome to the Ranch!
 
 
subject: Generic Casting
 
Threads others viewed
Parsing a TreeModel structure
Program keeps locking up, not sure why
I/O Issues
xml JAVA
NewLine Problem in Regular Expressions
WebSphere development made easy
without the weight of IBM tools
http://www.myeclipseide.com