Home > Software engineering >  Iterating through ArrayList of Objects in Java
Iterating through ArrayList of Objects in Java

Time:06-07

I have tried to find an answer to my question here but with no luck - please let me know if this was already answered and I will delete this question.

I want to iterate through an ArrayList of playing cards, here is my code:

public static void showCards(ArrayList<Card> cards){
    Iterator iterator = cards.iterator();
    while(iterator.hasNext()){
        String object = String.valueOf(iterator.next());
        System.out.println(object);
    }
}

I want to print the value of each card, but I am only getting the reference:

com.company.Card@4517d9a3
com.company.Card@4517d9a3

I have tried looping through as well - same thing. What am I doing wrong?

Card class if needed:

public class Card {
private CardSuit cardSuit;
private CardValue cardValue;

public Card(CardSuit cardSuit,  CardValue cardValue) {
    this.cardValue = cardValue;
    this.cardSuit = cardSuit;
}

public CardValue getCardValue() {
    return cardValue;
}

public CardSuit getCardSuit() {
    return cardSuit;
}

}

CodePudding user response:

Your code is more complicated than it needs to be:

  1. You can use a so called enhanced for loop instead of an Iterator. It's the same, but shorter.

  2. You don't have to call String.valueOf() or toString(). You can call System.out.println() for any object in java and it will automatically convert it to a String.

  3. If a while-loop only does one thing, you don't need the brackets.

The code now looks like this:

public static void showCards(ArrayList<Card> cards) {
    for (Card card : cards) System.out.println(card);
}

Because this is so simple, you might not even need showCards anymore, but could directly use a for-loop.


To convert an object to a String, java uses this weird notation:

full class name "@" hash code in hex

If you want java to convert a Card to a String a different way, you need to override the toString() method in your Card class:

public String toString() {
    return "Card with suit "   cardSuit   " and value   " cardValue;
}

(You will probably have to do the same for your classes CardSuit and CardValue).

CodePudding user response:

You can overrite default method toString:

public class Card {
...
@Overrite
public String toString() {
 return "{ cardSuit="   cardSuit   ", cardValue="   cardValue "}";
}

CodePudding user response:

also you can cast object to Card and use getCardValue():

public static void showCards(ArrayList<Card> cards){
    Iterator iterator = cards.iterator();
    while(iterator.hasNext()){
        Object object = iterator.next();
        Card c = (Card) object;
        System.out.println(c.getCardValue());
    }
}
  •  Tags:  
  • java
  • Related