Sign in to follow this  
honge

[java] Access data in an object that is in a vector

Recommended Posts

Hey, I am having a real problem with a piece of code that i am writing. Currently i have a card class and have filled a vector with instances of this. I now want to be able to access each of the objects variables (i.e, i want to print out the value of the card). So i guess my question is how is it possible to access the data in objects that are stored in a vector ? Any help would be greatly appreciated. Thanks for your time.

Share this post


Link to post
Share on other sites
If you know which index the card is at, you can use the elementAt(int index) function to return the object to you. Remember that you may have to typecast the object as a Card. Then just act on the Card as you would normally.

Share this post


Link to post
Share on other sites
Hi, thanks for taking the time to reply. I did manage to realise what i wasn't doing (casting) and fix it shortly after posting.

Thanks again.

Share this post


Link to post
Share on other sites
In JDK 1.5 you can use generics to declare what type of data your Collection holds.
ex:

Vector<Card> deck = new Vector<Card>();

// then you don't have to cast anymore
...
Card topOfDeck = deck.firstElement();



Of course, ArrayList is recommended over Vector nowadays (Vector is thread-safe I believe, which has performance issues for large collections), and mentioning Generics is opening up a can of worms, but I find them useful simply for the sake of not having to cast down from Object.

Share this post


Link to post
Share on other sites
Ah, ok. I didn't realise i could do that. Always nice to see other ways to do something, will go and do some further reading about it now :-)

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
That's really cool! I'm stuck in the stone age here in my CS classes with JDK 1.4.2. I wish I could do that. It would save me the trouble of having to write adapter classes to handle casting.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this