| Author |
vector methods and character input
|
Sue Hellinger
Greenhorn
Joined: May 26, 2005
Posts: 2
|
|
1. I have a class named 'node' and a vector made up of nodes. When I use a vector method like lastElement(), an Object is returned, not a node. However, I need a node to manipulate with as a result of this method call - for eg, I assign the node that I would like returned from the method to a newly created node. How do I tackle this? 2. How do I read character input from the console? i.e., objects of type 'char'? Thanks.
|
 |
Tim McGuire
Ranch Hand
Joined: Apr 30, 2003
Posts: 819
|
|
In response to number 1, cast it as a Node: if nodeVector is your vector, (Node)nodeVector.getLastElement() will return a Node instead of an object All java Collections work like this. (they pretend not to know what kind of objects they are holding and they make you tell them)
|
 |
Edwin Keeton
Ranch Hand
Joined: Jul 10, 2002
Posts: 214
|
|
Cast the Object type returned from lastElement() to a Node type. A char is a standard type, not an Object or reference type. You can read them using an implementation of java.io.Reader.read() to read System.in. Like this:
|
SCJP, SCWCD
|
 |
fred rosenberger
lowercase baba
Bartender
Joined: Oct 02, 2003
Posts: 9939
|
|
|
If you are positive that only Nodes will be in the vector, Tim's solution is perfect. if there is ANY chance there might be something OTHER than a node in there, you may want to use the 'instanceOf' operator to make sure before you do your cast.
|
Never ascribe to malice that which can be adequately explained by stupidity.
|
 |
Sue Hellinger
Greenhorn
Joined: May 26, 2005
Posts: 2
|
|
|
Thanks much.
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24041
|
|
If you're lucky enough to be using J2SE 5 (Tiger, aka JDK 1.5), you can use generics: Vector<Node> myVector = new Vector<Node>(); myVector.add(new Node()); ... Node aNode = myVector.lastElement(); Note that here the cast is unnecessary!
|
[Jess in Action][AskingGoodQuestions]
|
 |
 |
|
|
subject: vector methods and character input
|
|
|