• Post Reply Bookmark Topic Watch Topic
  • New Topic

Type Casting Question with DOM  RSS feed

 
Mike Mann
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was working with some code I found in a book (Parsing with DOM) and I ran into the following:


The question I have is why does Element need to be casted? Wouldn't

give you a Element Object?
If not, could you explain why.
Thanks for any Answers
[ December 24, 2004: Message edited by: Mike Mann ]
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Did you try it? The compiler message can be pretty informative sometimes. (And absolutely useless sometimes, too.) Anyhow, this would probably say something about not being able to turn a Node into an Element without an explicit cast.

If you look at your first line your itemlist variable is of type NodeList. And if you look at the doc for NodeList it only knows how to work with instances of Node. In fact it can hold instances of any object of type Node or any subinterface. Because Element extends Node, we say an "Element is a Node" so NodeList can hold objects of type Element with no problem.

If you get an object out of the list and it really is an Element you can cast it to Element. How do you know the Nodes in the NodeList are really Elements? Go back to the Document javadoc and see getElementsByTagName returns a "NodeList of all the Elements ...".

This is kinda slick. You can put an object instance of a class into a variable declared with any superclass or super interface. Document puts Element objects into a NodeList and you get them back out. Because you know what they are you feel safe casting them back to Element. But the compiler doesn't understand or trust that there are Elements in there. It makes you tell it with an explicit cast.

Hope that helps!!
 
Mike Mann
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Stan that helped me a lot! I appreciate that people are willing to spend time to help others.
[ December 24, 2004: Message edited by: Mike Mann ]
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's why we're here. It's a joy when it works!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!