如何寻址/访问动态创建的对象?

How to address / access dynamicly created Objects?

我尝试处理动态创建的对象以通过方法获取值。 我动态地创建了对象并使用了一个包含对象名称的 ArrayList。 我的 ArrayList 称为 arraylist,List 的值是由用户输入(扫描仪)创建的值是 f.e.("Mike","Nick","John").

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

}

这是我动态创建对象的地方:

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

如何从 Player-Class 获取特定的 Player-Value(fe:比方说,John 在移动,如何通过 get_counter1() 获取他的 counter1) 如何处理特定的玩家对象?

在此先感谢大家的回答!

迈克尔

听起来您需要 HashMap<String,Player> 来存储对您创建的 Players 的引用。

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

players 变量应该是创建玩家的 class 的成员,而不是局部变量。

然后你可以检索一个播放器:

    Player player = players.get("John");

您需要将玩家存储在地图中,该地图将玩家名称映射到玩家对象。

    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

如果您只有 List<Player> 而您正在使用 java 8,那么您可以使用流 API 按名称查找(或任何其他 属性 ).这将比使用 Map 慢,但您可以 search/map/etc 您的 collections 以更灵活的方式。

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

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