Sign in to follow this  

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

This topic is 4776 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
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
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
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

This topic is 4776 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.

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