我有一个工作方便的构造函数,但我觉得它的代码太多了。我不确定如何简化它,但我将不胜感激任何帮助!
public Hand(Card c1, Card c2, Card c3, Card c4, Card c5, Card c6) {
this();
this.card1 = c1;
this.card2 = c2;
this.card3 = c3;
this.card4 = c4;
this.card5 = c5;
this.card6 = c6;
if (c1 != null && c2 != null && c3 != null && c4 != null && c5 != null && c6 != null) {
for (int count = 0; count < 6; count++) {
if (count == 0) {
cardsInHand.add(c1);
} else if (count == 1) {
cardsInHand.add(c2);
} else if (count == 2) {
cardsInHand.add(c3);
} else if (count == 3) {
cardsInHand.add(c4);
} else if (count == 4) {
cardsInHand.add(c5);
} else if (count == 5) {
cardsInHand.add(c6);
}
}
}
}
编辑:根据下面的建议清理了代码。程序仍然运行,代码如下:
public Hand(Card c1, Card c2, Card c3, Card c4, Card c5, Card c6) {
this();
this.card1 = c1;
this.card2 = c2;
this.card3 = c3;
this.card4 = c4;
this.card5 = c5;
this.card6 = c6;
cardsInHand.add(c1);
cardsInHand.add(c2);
cardsInHand.add(c3);
cardsInHand.add(c4);
cardsInHand.add(c5);
cardsInHand.add(c6);
最佳答案
for 循环是多余的,因为它将按该顺序添加
cardsInHand.add(c1);
cardsInHand.add(c2);
//etc
会做同样的事情。
您还可以考虑使用 var args 构造函数:
public Hand(Card ... cards){
this.card1=cards[0];
//etc
关于java - 简化便利构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19738863/