2013-10-18 10 views
0

새로 생성 된 객체를 클래스 생성자의 ArrayList에 추가하려고합니다. 새 메소드는 main 메소드의 다른 클래스에서 작성됩니다.생성자 (Java)의 ArrayList에 새 객체 추가

홈페이지 방법 :

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는 새 Player()를 사용합니다. "this"의 개념을 설명하기 위해 –

+0

나는 결국 그것을 할 수 있었다. 그리고 그것은 정확하게이 선을 따라 있었다. 감사. – Chris

2

실제로는 인 것처럼 들리 겠지만 실제로 구성중인 인스턴스를 참조하는 방법을 묻는 질문은입니다.
키워드의 의미는 this입니다.

+0

그는 기본 생성자가 없기 때문에'new Player()'가 작동하지 않는 이유로 실패합니다. – DarthVader

+0

@DarthVader : 그렇습니다.하지만 어쨌든 말이되지 않습니다. – SLaks

+0

@DarthVader 나는 OP가 새로운 Player()를 사용하여 "this"의 개념을 표현한다고 생각합니다. –

0

이 게시물 오래된,하지만 비슷한을 필요로하는 사람을 위해 I는 다음과 같이 그 일을 제안 :

Main 클래스 :

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

} 

일반적으로 당신은 정적 사용하지 않아야합니다 키워드는 해당 클래스의 각 인스턴스마다 다른 변수에 있어야합니다. 내부에 물건이 들어 가지 않도록하십시오.