Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
按id获取java对象_Java - Fatal编程技术网

按id获取java对象

按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

我试图实现的是仅使用对象的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");
        }
    }
    
    公共类林{
    公共字符串名称;
    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分钟内接受这个答案(我)