Get java object by id

时间:2016-04-04 18:32:37

标签: java

What I am trying to achieve is to update an object's value with only his ID known. How can I get the object with a corresponding ID, so I can update a property? I tried to make this question more general by using a simple example with trees. Hopefully this will make the problem more clear than just pasting my project code here.

class forest

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");
    }
}

class tree

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

1 个答案:

答案 0 :(得分:1)

Use HashMap to keep objects. Then use the get method to get the object with the given 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");
    }
}