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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Iterating over a vactor with objects

Status
Not open for further replies.

Stovio

Programmer
Mar 20, 2002
30
SE
Hi,

This is probably really easy for many of you but i have failed to find the solution. I want to iterate over a vector containing objects of a class i have defined. In every iteration I want to print out some of the member variables of the object. Now, every example i have come across simply casts the entire object in the vector to a String but that is not possible when the objects contains various variables. I was hoping for something as simple as this, but it does nt work:

public Vector getDiscoveryResult(){
Iterator i = servers.listIterator();
while(i.hasNext()){
ServerInfo s = i.next(); //error
System.out.println("IP: " + s.address + ", PORT: " + s.port);
}
return servers;
}

Thanks for any help.

/H
 
Servers is a vector containing ServerInfo objects. ServerInfo contains only the variables address and port.
 
You need to cast the object.

ServerInfo s = (ServerInfo) i.next();

After that, you can access the variables, if they are public.

Cheers.

Dian
 
Change :

ServerInfo s = i.next(); //error

to

ServerInfo s = (ServerInfo)i.next(); //error

i.next() returns an Object - so you must cast it to your particular object.

Or you could write a toString() and override the Object.toString() method which prints out what you want.

So the code would then look like :

Object s = i.next();
System.out.println(s);



--------------------------------------------------
Free Database Connection Pooling Software
 
oops, posting at the same time there Dian.

--------------------------------------------------
Free Database Connection Pooling Software
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top