You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java:如何通过构造参数id获取对象的其他属性

Solution: Map Character IDs to Objects for Easy Lookup

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: HashMap provides 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 09:03:56