2013-10-18 70 views
0

我想将新创建的对象添加到类的构造函数中的ArrayList中。新对象正在主方法的另一个类中创建。将新对象添加到构造函数中的ArrayList(Java)

主要方法:

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

'name'和'age'不应该是静态的。 – SLaks

+1

你可以尝试'players.add(this)'这个参考你当前的实例,但我的建议是修改你的结构,因为我认为它不应该是玩家有责任记住迄今为止创建了哪些玩家。这个功能应该委托给一个专门的实体 – Morfic

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


} 
+0

只需添加一个默认构造函数就可以创建一个具有添加到arraylist中的**不同**新玩家的玩家,OP将使用新玩家()解释“这个”的概念 –

+0

我最终设法做到了这一点,它完全是沿着这些路线。谢谢。 – Chris

2

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

+0

没有。他失败了,原因是'new Player()'不会工作,因为没有默认的构造函数。 – DarthVader

+0

@DarthVader:是的,但这无论如何也没有意义。 – SLaks

+0

@DarthVader我认为OP使用新的Player()来表达“this”的概念 –

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. 
} 

Player类:

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

} 

一般来说,你应该避免使用静态变量的关键字应该在该类的每个实例中都有所不同。避免在里面有自己的对象。