繁体   English   中英

我的getter函数放在哪里?

[英]Where do I put my getter function?

下面的类是一个上下文生成器,它将Tree对象放置在网格的地理空间中。 我创建了具有各种适用性值和id的树对象的数组列表:

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; 

}


}   

我相信我可以使用吸气剂来访问其他课程中的列表。 像这样

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

但是我的问题是:我将代码放在哪里? 每当我放置它时,都会出现错误,特别是“ return tree;”。

另外:我还可以使用getter从列表中获取maxTree值吗?

不在这种情况下。

通常,使用吸气剂来访问字段。 build方法中将trees声明为局部变量。 这意味着每次调用它时,您都会得到一个新列表,并且从该方法返回后,该列表将不再存在。

如果您确实要存储树列表(我不确定为什么要这么做),则必须将其移至字段声明:

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

maxTree值也存在类似问题; 如果您想存储它,并且看起来确实适合保留您的实例,那么您也必须将其移动到字段中。 它不像上面的声明那样简单明了,因为您只知道该方法内部的值,但是它的调用不应该比它复杂得多。 我把它留给读者练习。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM