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

Started by
4 comments, last by GameDev.net 19 years, 5 months ago
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.
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.
www.aidanwalsh(.net)(.info)
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.
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.
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 :-)
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.

This topic is closed to new replies.

Advertisement