Trying to return Multiple Card objects from a hashmap

Currently using the following code

private HashMAp<Integer,Card> allCards = new HashMap<Integer,Card>();

public Card getAllCards()
    Collection col = allCards.values();

    for(Card c: col)
        return c;

This works but only returns 1 Card object from many.

How can I change it to return every object stored in the HashMap??


Recommended Answers

All 7 Replies


while(Card c: col)
        return c;


for(int i = 0; i < col.length(); i++)
return c;

**These may work or may not, I only started learning java for 2-3 months now. Forgive me if these don't work :3

I don't think these will work as the method stops running once the return statement is executed. Or at least thats my belief. I'd rather not return any sort of array or collection aswell as I want all processing of Card data to be done in the specified class.

Therefore I require a way of taking every object in the hashmap and returning them to the client method.

Hmmm... Okay, I can't figure that one out. Sorry T_T

Yes, as soon as it hits the return statemnent it returns, so you only ever get the first Card.
Your requirenent seems bizarre - you want to return multiple Cards, but not use an array or Collection? Given that, all I can think of is to return an Iterator or ListIterator that will allow the calling program to iterate through the Cards, but frankly an array would be easier for everybody.

public Card[] getAllCards() {
    Card[] arr=new Card[allCards.length()];
    int i=0;
    for(Card c:col) {
    return arr;

... or maybe just

   return allCards.values().toArray(new Card[0]);

... why write code when its already in the API?

Thankyou for the responses.

I know the requirement was strange. It's what made the problem so difficult. I have now relented and returned an Array.

Once again thank you for the responses. They were very helpful.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.