Search code examples
javaarraylistequalscontain

Not Finding Object in ArrayList


I am creating a deck of 20 cards. Each of them are assigned Integer president from 1-10. The deck should be as follows: 1, 1, 2, 2, 3, 3, ... 17, 17, 18, 18, 19, 19, 20, 20

The contains search says that it is a new card in the deck every time. I believe there may be something wrong with my equals() method, but I am not sure. Any ideas?

//Class MainClass

public void createDeck() {
    cards = new ArrayList<President>();
    President temp;
    for (int i = 1; i <= 20; i++) {
        do {
            temp = new President(i, rand(20));
            System.out.println(cards.contains(temp));
        } while (cards.contains(temp));
        cards.add(temp);
        System.out.println(cards.size());
    }
    for(President p : cards){
        while(p.getPresident() > 10){
            p.setPresident(p.getPresident() - 10);
        }
        System.out.println("" + p.getPresident());
    }

}

//Class President

public class President {

private int president;
private int card;

public President(int card, int president) {
    super();
    this.card = card;
    this.president = president;

}

@Override
public boolean equals(Object o) {
    if(o instanceof President){
        President p = (President) o;
        if(p.getPresident() == this.president && p.getCard() == this.card){
            return true;
        }
    }
    return false;

}

private int getCard() {
    // TODO Auto-generated method stub
    return card;
}

public int getPresident() {
    // TODO Auto-generated method stub
    return president;
}

public void setPresident(int president) {
    // TODO Auto-generated method stub
    this.president = president;
}

}


Solution

  • Rather than going about it this way, I recommend populating the deck in order, then shuffling it:

    cards = new ArrayList<President>(20);
    for (int i = 1; i <= 20; i++) {
        cards.add(new President(i, i));
    }
    Collections.shuffle(cards);
    

    From the Collections.shuffle documentation:

    Randomly permutes the specified list using a default source of randomness. All permutations occur with approximately equal likelihood.