带有数组的java构造函数

nc1teljy  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(287)

今天我试着编写一个程序,用它来管理虚拟足球运动员。现在我有一个问题,我不知道如何初始化构造函数中另一个类的数组。
这是我的“团队”宣言

Manager managerOfBayern = new Manager("Manager1",55,125);
Manager managerOfBvb = new Manager("Manager2",60,122);
Team fcBayern = new Team(managerOfBayern,playerArrFcB,"FcBayern");
Team bvb = new Team(managerOfBvb,playerArrBvb,"Bvb");

现在我要初始化我的团队。

public class Team {

Manager theManager;
Player[] thePlayer;
String name;

public Team(Manager theManager, Player[] thePlayer, String name) {
    this.theManager = theManager;
    for (int i = 0; i < thePlayer.length; i++) {
        thePlayer[i] = thePlayer[i];
    }
    this.name = name;
}

但是如何正确初始化数组(theplayer)
我希望你们能帮我解决这个问题。。。。。

4xrmg8kj

4xrmg8kj1#

你所做的几乎是正确的!
就在数组初始化的一部分,也就是你在复制数组的构造函数中运行的for循环中,只需将操作符“=”的左侧替换为“this.theplayer[i]”,并且你还需要事先指定数组的大小,以便在for循环中使用它,即生成的构造函数代码应该是这样的

public Team(Manager theManager, Player[] thePlayer, String name) {
    this.theManager = theManager;
    this.thePlayer = new Player[thePlayer.length];
    for (int i = 0; i < thePlayer.length; i++) {
        this.thePlayer[i] = thePlayer[i];
        //or this.thePlayer[i] = new Player(thePlayer[i]); in case you want true deep copy, then in Player class you make a constructor of this signature(also known as copy constructor) and copy all the properties of Object passed as an argument  
    }
    this.name = name;
}

相关问题