• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

vector methods and character input

 
Sue Hellinger
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 820
IntelliJ IDE Tomcat Server VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 214
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:

 
fred rosenberger
lowercase baba
Bartender
Pie
Posts: 12102
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Sue Hellinger
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks much.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic