• Advertisement
Sign in to follow this  

Trouble with Java Vector

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

I've been working on my Card game classes and while I was doing the players Hand class (It hold's a specific amount of Cards in an array) I realized that it would be much easier to use a vector to hold the data instead of an array. The vector also has the functions that I was writing myself. I tried out the vector but I run into errors. Some of my functions return a Card object, and my vector is holding Card elements, but when I return the vector I get an error saying the types are incompatible. It requires a Card but get's a java.lang.object... Well isn't my Vector holding Card objects and returning Card objects? I also didn't see anything about creating a specific type of vector, like you do in C++. (Vector<int> etc..) So that may be one source of the problem. Any help would be great. Here's some source
class Hand
{
	private int handAmount;
	private Vector hand;
	
	Hand(int amount)
	{
		handAmount = amount;
		numCardsInHand = amount;
		hand = new Vector(handAmount, 1);
	}
	
	public void CreateHand(Deck d)
	{
	    for (int i = 0; i < handAmount; i++)
		hand.addElement(d.TakeFromTop());		
	}

       // here's one function that return's a Card

        public Card PassFromTop()
	{
	   if (!Empty())
	   {
		return hand.firstElement();
	   }
	}


Share this post


Link to post
Share on other sites
Advertisement
Java collections store everything as an Object. You'll need to cast to the type you want, which is Card in this case.


public Card PassFromTop()
{
if (!Empty())
{
// Collection returns Object; cast to Card.
return (Card)hand.firstElement();
}
}

Share this post


Link to post
Share on other sites
You may also try using the List implementation of the vector class:

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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement