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

时间:2013-10-18 18:41:24

标签: java class object arraylist

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

   }
}

任何帮助都非常感激。

3 个答案:

答案 0 :(得分:3)

您必须编辑

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


}

答案 1 :(得分:2)

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

答案 2 :(得分: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关键字。避免让自己的对象进入。