1

我正在尝试将新创建的对象添加到类的构造函数中的 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
    
   }
}
4

3 回答 3

6

您必须编辑该行

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


}
于 2013-10-18T18:51:45.263 回答
2

听起来您实际上是在询问如何引用您正在构建的实例。
这就是this关键字的作用。

于 2013-10-18T18:44:07.527 回答
0

这篇文章很旧,但对于有类似需求的人,我建议这样做:

主类:

public static void main(String[] args) {
    //TODO code application logic here
    java.util.List<Player> players = new java.util.ArrayList<>(); //list to hold all players
    Player p1 = new Player("Peter"); //test player
    players.add(p1); //adding test player to the list
    players.add(new Player("Peter")); //also possible in this case to add test player without creating variable for it.
}

球员等级:

public class Player {

    private final int age = 15; //if you always going to use 15 as a age like in your case it could be final. if not then pass it to constructor and initialize the same way as the name.
    private String name;

    Player(String name) { //variable name can be the same as one in class, just add this prefix to indicated you are talking about the one which is global class variable.
        this.name = name;
    }

}

通常,您应该避免在该类的每个实例中应该不同的变量上使用 static 关键字。避免内部有自己的对象。

于 2017-11-08T07:40:59.203 回答