Reputation: 7569
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;
}
}
Upvotes: 0
Views: 113
Reputation: 9741
Your equals is perfectly fine. Looks like a logical mistake to me:
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());
}
This will generate 20/4000 possible combinations. If you want (1,1)(2,2)....(20,20), your current loop may generate (1,11)(2,13)...(20,5).
Also, cards.contains(temp)
will never be true, because i is changed each time.
I am still not sure what exactly are you trying to do? If its just shuffle the deck @PaulBellora's answer seems correct.
Upvotes: 3
Reputation: 2085
cards.contains(temp) is never "true" in the do-while loop becaues every President have a other card number.
Upvotes: 2
Reputation: 55223
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.
Upvotes: 2