我试图在列表中计算一个对象的出现次数,但似乎不起作用。
这是我的类 Card:
public class Card {
private int value;
private String type;
private String color;
}
我正在尝试设置一副104张牌的卡组,其中包含每张牌的2个实例,但看起来我的条件不正确:
public static List<Card> InitializeDeck(){
for(int i=0;i<104;i++){
boolean isOk = true;
while (isOk){
int col = (int) (Math.floor(Math.random() * 2) + 1);
if (col == 1) {
color = "Black";
} else {
color = "Red";
}
value = (int) (Math.floor(Math.random() * 14));
while (value == 0) {
value = (int) (Math.floor(Math.random() * 14));
}
int ty = (int) (Math.floor(Math.random() * 4));
switch (ty) {
case 0:
type = "Spade";
break;
case 1:
type = "Heart";
break;
case 2:
type = "Diamond";
break;
case 3:
type = "Club";
break;
}
Card card = new Card(value, type, color);
if(deck.isEmpty() || deck.stream().filter(line -> card.equals(line)).count()<=1){
deck.add(card);
isOk=false;
}
}
}
return deck;
}
我得到了一副104张牌的牌组,但有时同一张牌会出现4次,甚至可能没有任何一次出现,有什么提示吗?
Card
类中重写了equals()
方法吗? - Benjamin Urquhart