Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

java.util.Vector & casting

Status
Not open for further replies.

JavaNewbie

Programmer
Nov 26, 2000
1
0
0
CA
I am tring to create a new variable of type Node (which I created myself; it's an object), and I am trying to pass it the lastElement() of the Vector, which contains only Node elements.

(i.e. Node temp = (Node) vectorObject.lastElement();)

However, it simply throws an exception (ClassCastException)and quits on me. If I remove the cast, it tells me that I need an "explicit cast need to convert java.lang.Object to Node" Any help is appreciated
 
/*
Here is some complete sample using Vector and Node.
Hope it will help.

*/
import java.util.*;

/**
Written by : M.Gareil 27 Nov 2k
*/

public class Driver
{
public static void main( String [] args )
{
Vector nodes ;
nodes = new Vector() ;
nodes.addElement(new Node(1)) ;
nodes.addElement(new Node(2)) ;
nodes.addElement(new Node(3)) ;
nodes.addElement(new Node(4)) ;

// There are 4 Node objects in the Vector now

Node tmp = (Node)nodes.lastElement() ;

System.out.println("What's the value of the last Node ? : " + tmp.getMember());


}
}
//=================================
/**
Written by : M.Gareil 27 Nov 2k
*/
public class Node
{
int someMemberHere ;
public Node( int arg )
{
someMemberHere = arg ;
}
int getMember()
{
return this.someMemberHere ;
}
}
//===============================
 
i think you might have a simple problem with brackets i think you'll find that the cast is taking a vector and trying to cast it to a node, not what you want, instead you want to retrieve the last element then cast that to a node so try [tt]Node temp = (Node) [red]([/red]vectorObject.lastElement()[red])[/red];[/tt]
this may not be your problem because i've made similar errors using collections and got a lot of error messages

Chris Packham
kriz@i4free.co.nz

A thousand mokeys at a thousand machines, it happened, it got called the internet.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top