我想要实现的是只用已知的 ID 来更新对象的值:
- 如何获取具有相应 ID 的对象?
- 以便我可以更新属性?
类森林
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/