java - 通过id获取java对象

标签 java

我想要实现的是只用已知的 ID 来更新对象的值:

  1. 如何获取具有相应 ID 的对象?
  2. 以便我可以更新属性?

类森林

public class forest {
    public forestName;
    
    public forest(String forestName){
        this.forestName=forestName;
    }
    updateTreeName(int id, String Name){
        // Here I need to update the name of the tree with that specific ID
    }

    public static void main(String[] args) {
        forest greenforest = new forest();
        // create some tree's in the greenforest.
        greenforest.updateTreeName(4, "red leafe");
    }
}

类树

public class tree {
    public String treeName;
    public int id;
    public tree(int id, String treeName){
        this.treeName=treeName;
        this.id=id;
    }
}

最佳答案

使用HashMap来保存对象。然后使用 get 方法获取具有给定 id 的对象。

public class Forest {
    public String forestName;

    HashMap<Integer, Tree> trees = new HashMap<>();

    public Forest(String forestName){
        this.forestName=forestName;

        //initialize trees
        trees.put(4, new Tree(4, "redleaef"));
    }

    public void updateTreeName(int id, String Name){
        trees.get(id).treeName = Name;
    }

    public static void main(String[] args) {
        Forest greenforest = new Forest("name");
        // create some tree's in the greenforest.
        greenforest.updateTreeName(4, "red leafe");
    }
}

关于java - 通过id获取java对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36410221/

相关文章:

java - 如何使用Camel解压加密的zip文件

Java - 如何比较 Guava 范围?

java - GLSL 阵列不工作

Java Date 构造函数意外行为

java - 哈希集如何发生冲突?

java - 当指定 -vcodec 副本时,FFmpeg 挂起(通过 ProcessBuilder 从 Java 调用)

java - 如何在 java.sql.Timestamp 中添加时间

Java方法对两个一维数组求和

java - 将 Logistic 回归损失函数转换为 Softmax

java - 如何以编程方式发送带参数的 HTTP 请求?