简体   繁体   中英

Get object's parameter with another parameter that is passed in method - Java

I've created 4 charater objects with 4 parameters, which includes id. How can I access another parameter of object with one of its constructor parameters? For example, I want to create a method which will take id as a parameter and with that id, I want to specify on which character is user talking about, so I can get that specific character's parameters(Name etc).

character objects

    Character warrior = new Character("Warrior", 60, 15+rn.nextInt(5), 1); //name, health, damage, id
    Character skeleton = new Character("Skeleton", 90, 20+rn.nextInt(10), 2);

Method I am trying to create

public void spawnEnemy(int id){
    System.out.printf("%s appeared!", //get character's name with id);

}

If all Character has a unique id , you can put them into a java.util.HashMap :

HashMap<Integer, Character> map = new HashMap<>();
Character warrior = new Character("Warrior", 60, 15+rn.nextInt(5), 1);
map.put(1, warrior);

Then you can call get the warrior with id 1 :

public void spawnEnemy(int id){
    System.out.printf("%s appeared!", map.get(id));
}

您可以创建全局哈希图,也可以将<Integer, Character>的哈希图传递给您的方法以快速查找字符

If you can modify the Character class, you can give it a static, ie "global," Map to keep track of all instances. That way, client code doesn't have to worry about keeping track.

public class Character {

  // "Global" Map that tracks all Character instances by ID
  private static HashMap<Integer, Character> idToCharacter = new HashMap<>();

  // Fields, etc...

  public Character(String name, int health, int damage, int id) {
    // Set field values, etc...

    // Track this new Character
    idToCharacter.put(id);
  }

  // "Global" method for getting a Character by ID
  public static Character getCharacter(int id) {
    return idToCharacter.get(id);
  }

}

Then your client code simply calls getCharacter :

public void spawnEnemy(int id){
  System.out.printf("%s appeared!", Character.getCharacter(id).getName());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM