M. Eimire
M. Eimire

Reputation: 15

How to address / access dynamicly created Objects?

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

Upvotes: 3

Views: 53

Answers (3)

Bal&#225;zs &#201;des
Bal&#225;zs &#201;des

Reputation: 13807

If you only have a List<Player> and you are using java 8, then you can use the stream API to find by name (or any other property). This will be slower than using a Map, but you can search/map/etc your collections in a more flexible way.

Optional<Player> optPlayer = arraylist
    .stream()
    .filter(p -> "John".equals(p.get_playerName()))
    .findFirst();

if(optPlayer.isPresent()) {
    //player found
    Player p = optPlayer.get();
}

Upvotes: 0

peter.petrov
peter.petrov

Reputation: 39477

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

Upvotes: 2

Eran
Eran

Reputation: 393936

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

Upvotes: 1

Related Questions