yoano
yoano

Reputation: 1546

Get java object by id

What I am trying to achieve is to update an object's value with only his ID known:

  1. How can I get the object with a corresponding ID?
  2. So that I can update a property?

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

Upvotes: 1

Views: 7546

Answers (1)

rdonuk
rdonuk

Reputation: 3956

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

Upvotes: 1

Related Questions