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

时间:2015-02-19 12:25:53

标签: java object

我尝试解决动态创建的对象以通过方法获取值。 我动态地创建了对象,并使用了一个包含对象名的ArrayList。 我的ArrayList被称为arraylist,List的值由users-input(Scanner)创建。值为f.e。(“Mike”,“Nick”,“John”)。

我的班级“玩家”:

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

我如何从玩家级获得特定的玩家价值(fe:让我们说,约翰正在移动中,如果通过get_counter1()得到他的反击1) 如何处理特定的Player-Object?

非常感谢大家回答!

迈克尔

3 个答案:

答案 0 :(得分:2)

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

    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

答案 1 :(得分:1)

听起来您需要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变量应该是创建玩家的类的成员,而不是本地变量。

然后您可以使用以下内容检索播放器:

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

答案 2 :(得分:0)

如果您只有List<Player>且使用的是Java 8,则可以使用流API按名称(或任何其他属性)进行查找。这比使用Map慢,但您可以更灵活地搜索/映射/等等您的收藏。

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

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