Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to address / access dynamicly created Objects?

Tags:

java

object

i try to address dynamicly created Objects to get values via methods. I crated the Objects dynamicly and used a ArrayList which helds the objectnames. My ArrayList is called arraylist and the values of the List are created by users-input (Scanner) The values are f.e.("Mike","Nick","John").

My class "Player":

public class Player {

    String playerName = "Player";
    int counter1 = 20;
    int counter2 = 50;

    public String get_playerName(){
        return playerName;
    }    
    public int get_counter1(){
        return counter1;
    }    
    public int get_counter2(){
        return counter2;
    }    


    public Player(String Name){
    playerName = Name;
    }

}

Here's where i created the Objects dynamicly:

int playersCount = arraylist.size(); //Size of ArrayList with Players names

//create Players dynamicly
for(int i = 0; i < playersCount; i++){
     Player playerName = new Player(arraylist.get(i));
}

How can i get a specific Player-Value from Player-Class (fe: let's say, John is on the move, haw to get his counter1 via get_counter1()) How to address a specific Player-Object ?

Thanks alot in advance to everybody answering!

Michael

like image 926
M. Eimire Avatar asked Nov 27 '25 12:11

M. Eimire


2 Answers

You need to store the players in a Map which maps the player names to the player objects.

    HashMap<String, Player> mp = new HashMap<String, Player>();
    for(int i = 0; i < playersCount; i++){
           Player player = new Player(arraylist.get(i));
           mp.put(arraylist.get(i), player);
    }


    // ... 

    Player p = mp.get("John");

    // now use the player John i.e. the p object
like image 97
peter.petrov Avatar answered Nov 30 '25 00:11

peter.petrov


It sounds like you need a HashMap<String,Player> to store the references to the Players you create.

    int playersCount = arraylist.size(); //Size of ArrayList with Players names
    Map<String,Player> players = new HashMap<>();

    //create Players dynamicly
    for(int i = 0; i < playersCount; i++){
        Player player = new Player(arraylist.get(i));
        players.put (arraylist.get(i), player);
    }

The players variable should be a member of the class that creates the players, not a local variable.

Then you can retrieve a player with :

    Player player = players.get("John");
like image 41
Eran Avatar answered Nov 30 '25 02:11

Eran