gpt4 book ai didi

java - 在构造函数中将新对象添加到 ArrayList

转载 作者:行者123 更新时间:2023-11-29 07:06:14 25 4
gpt4 key购买 nike

我正在尝试将新创建的对象添加到类的构造函数中的 ArrayList。新对象正在 main 方法中的另一个类中创建。

主要方法:

public static void main(String[] args) {
// TODO code application logic here
Player p1 = new Player("Peter");
}

我的播放器类:

public class Player {

protected static int age;
protected static String name;
protected static ArrayList players = new ArrayList();

Player(String aName) {

name = aName;
age = 15;
players.add(new Player()); // i know this doesn't work but trying along these lines

}
}

最佳答案

你必须编辑行

players.add(new Player());

players.add(this);

另外,年龄和名字也没有必要做成静态的

我建议你改用下面的代码

import java.util.ArrayList;

public class Player {

protected int age; //static is removed
protected String name; // static is removed
protected static ArrayList<Player> players = new ArrayList<Player>(); //this is not a best practice to have a list of player inside player.

Player(String aName) {

name = aName;
age = 15;
players.add(this); // i know this doesn't work but trying along these lines

}


public static void main(String[] args) {
// TODO code application logic here
Player p1 = new Player("Peter");
}


}

关于java - 在构造函数中将新对象添加到 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19456860/

25 4 0