permaculture playing cards
The moose likes Beginning Java and the fly likes vector methods and character input Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "vector methods and character input" Watch "vector methods and character input" New topic

vector methods and character input

Sue Hellinger

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'?

Tim McGuire
Ranch Hand

Joined: Apr 30, 2003
Posts: 820

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 to read Like this:

fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11955

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.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Sue Hellinger

Joined: May 26, 2005
Posts: 2
Thanks much.
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

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]
I agree. Here's the link:
subject: vector methods and character input
It's not a secret anymore!