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
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
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With