在构造函数中向 ArrayList 添加新对象

chr*_*ris 1 java class arraylist object

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

主要方法:

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

我的播放器类:

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
    
   }
}
Run Code Online (Sandbox Code Playgroud)

shi*_*ari 5

您必须编辑该行

players.add(new Player());
Run Code Online (Sandbox Code Playgroud)

players.add(this);
Run Code Online (Sandbox Code Playgroud)

此外,无需将年龄和名称设为静态

我建议你应该使用以下代码

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");
}


}
Run Code Online (Sandbox Code Playgroud)