Jump to content
  • Advertisement
Sign in to follow this  
honge

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

This topic is 4996 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!