java - 简化便利构造函数

标签 java

我有一个工作方便的构造函数,但我觉得它的代码太多了。我不确定如何简化它,但我将不胜感激任何帮助!

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/

相关文章:

java - PDFBox U+00A0 在此字体编码中不可用

java - 使用java解析csv文件

java - 无法加载主类 list 属性

java - 在 J3A081 上安装小程序(Java 卡)

java - 对于设置字体大小,android sp、px 或 pt 中最喜欢的字体大小

Java方法用Reflection给对象字段赋值

java - JPA中的显式和隐式JOIN有什么区别? (表现)

java - 在java中将字节数组传递给fileinputstream的方法

java - 套接字代码创建新的作家?

java - 如何配置串行端口并与之通信?