按id获取java对象
我试图实现的是仅使用对象的ID更新对象的值:按id获取java对象,java,Java,我试图实现的是仅使用对象的ID更新对象的值: 如何获取具有相应ID的对象 这样我就可以更新属性了 类森林 public class forest { public forestName; public forest(String forestName){ this.forestName=forestName; } updateTreeName(int id, String Name){ // Here I need to
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");
}
}
公共类林{
公共字符串名称;
HashMap树=新的HashMap();
公共林(字符串forestName){
this.forestName=forestName;
//初始化树
树。放(4棵,新树(4棵,红杉);
}
public void updateretreename(int-id,字符串名){
trees.get(id).treeName=Name;
}
公共静态void main(字符串[]args){
森林绿色森林=新森林(“名称”);
//在绿林中创建一些树。
greenforest.updateTreeName(4,“红叶”);
}
}
有很多方法:保留映射
并通过id找到树
对象。在树
上实现.equals()
方法,并将其放入集合
;遍历查看名称的所有树
对象。这些要求将带来更好的答案(编辑成森林
到树
)!你以前的编辑也非常冗长。我会在2分钟内接受这个答案(我)