Java:如何通过构造参数id获取对象的其他属性
Hey there! The cleanest and most efficient way to solve this problem is to use a Map (specifically a HashMap) to store a direct mapping between each character's ID and the corresponding Character object. Here's how to implement it step by step:
Step 1: Set Up a Map to Store Character Entries
First, create a Map<Integer, Character> where the key is the character's ID, and the value is the Character instance itself. This lets you look up any character by ID in near-instant time.
Step 2: Initialize and Populate the Map
When you create your Character objects, add them to the map using their ID as the key. Make sure your Character class has getter methods for id and name (and any other properties you need to access later).
Step 3: Implement the spawnEnemy Method
In your lookup method, use the input ID to fetch the character from the map. Always add a null check to avoid runtime errors if an invalid ID is passed.
Full Example Code
import java.util.HashMap; import java.util.Map; import java.util.Random; public class GameManager { private Random rn = new Random(); // Map to link character IDs to their objects private Map<Integer, Character> characterRegistry = new HashMap<>(); public GameManager() { // Create your characters and register them in the map Character warrior = new Character("Warrior", 60, 15 + rn.nextInt(5), 1); Character skeleton = new Character("Skeleton", 90, 20 + rn.nextInt(10), 2); characterRegistry.put(warrior.getId(), warrior); characterRegistry.put(skeleton.getId(), skeleton); } public void spawnEnemy(int id) { Character enemy = characterRegistry.get(id); if (enemy != null) { System.out.printf("%s appeared!", enemy.getName()); } else { System.out.println("Error: No enemy exists with ID " + id); } } } // Your Character class with required getters class Character { private String name; private int health; private int damage; private int id; public Character(String name, int health, int damage, int id) { this.name = name; this.health = health; this.damage = damage; this.id = id; } // Getters for accessing properties public String getName() { return name; } public int getId() { return id; } // Add other getters/setters as needed for health, damage, etc. }
Why This Works
- Efficiency:
HashMapprovides O(1) average time complexity for lookups, which is way better than looping through a list every time you need to find a character. - Maintainability: If you add more characters later, you just need to call
characterRegistry.put()once—no extra code changes required for lookup logic. - Safety: The null check ensures your code doesn't crash if someone passes an invalid ID.
Alternative: Using an Array (If IDs Are Continuous)
If your character IDs are consecutive integers starting from 1, you could use an array instead. For example:
private Character[] characters = new Character[3]; // IDs 1,2 fit here // In constructor: characters[1] = warrior; characters[2] = skeleton; // In spawnEnemy: if (id > 0 && id < characters.length) { Character enemy = characters[id]; // ... }
But this is less flexible if IDs are non-consecutive or might change later. The Map approach is almost always the better choice for this scenario.
内容的提问来源于stack exchange,提问作者Tom.Achki

