Search code examples
javagetter-setter

Where do I put my getter function?


The class below is a context builder which places Tree objects in geographic space on a grid. I have created an array list of trees objects with various suitability values and ids:

public class TreeBuilder implements ContextBuilder<Object> {


@Override
public Context build(Context<Object> context) {
    context.setId("taylor");

    ContinuousSpaceFactory spaceFactory = 
    ContinuousSpaceFactoryFinder.createContinuousSpaceFactory(null);
    ContinuousSpace<Object> space = 
    spaceFactory.createContinuousSpace("space", context, 
            new RandomCartesianAdder<Object>(), 
            new repast.simphony.space.continuous.WrapAroundBorders(), 
            50, 50);


    GridFactory gridFactory = GridFactoryFinder.createGridFactory(null);
    Grid<Object> grid = gridFactory.createGrid("grid", context, 
            new GridBuilderParameters<Object>(new WrapAroundBorders(), 
            new SimpleGridAdder<Object>(), 
            true, 50, 50));

    ArrayList<Tree> trees = new ArrayList<Tree>();

    int treeCount = 100;
    for (int i = 1; i < treeCount; i++) {
        double suitability = Math.random();
        int id = i;


    Tree tree = new Tree(space, grid, suitability, id);
    context.add(tree);
    trees.add(tree);



    tree.measureSuit();

    }

    Tree maxTree = Collections.max(trees, new SuitComp());
    System.out.println(maxTree);

    for (Object obj : context) {
        NdPoint pt = space.getLocation(obj);
        grid.moveTo(obj, (int)pt.getX(), (int)pt.getY());

    }


    return context; 

}


}   

I believe I can use a getter to access the list in other classes. Something like this...

public ArrayList<Tree> getList() {
return trees;
}

But my question is: Where do I put the code above? I get an error whenever I place it, specifically with "return trees;".

In addition: Can I also use a getter to get the maxTree value from the list?


Solution

  • Not in this context.

    One generally uses a getter to access a field; trees is declared as a local variable in the method build. This means that every time it's called, you get a new list, and it no longer exists once you've returned from the method.

    If you really want to store the trees list (and I'm not sure why you would want to), you would have to move it to a field declaration:

    private List<Tree> trees = new ArrayList<>();
    

    A similar issue exists with the maxTree value; if you want to store that, and that does seem like something reasonable to keep with your instance, then you'd have to move that to a field as well. It's not as straightforward as the declaration above, as you'd only know what the value is inside of that method, but its invocation shouldn't be much more complicated than it. I leave that as an exercise to the reader.