我创建了一个树类并实现了一个比较器:
class SuitComp implements Comparator<Tree> {
@Override
public int compare(Tree o1, Tree o2) {
return Double.compare(o1.getSuit(), o2.getSuit());
}
}
class Tree {
private ContinuousSpace<Object> space;
private Grid<Object> grid;
public double suitability;
public int id;
public static int count = 1;
public Tree(ContinuousSpace<Object> space, Grid<Object> grid, double suitability, int id) {
this.space = space;
this.grid = grid;
this.id = count;
count++;
}
public double getSuit() {
return suitability;
}
public void setSuit(double suitability) {
this.suitability = suitability;
}
@Override
public String toString() {
return "Tree " + id + " is the most suitable, with a value of: " + suitability;
}
public void measureSuit() {
System.out.println("Tree number " + id + " has a suitability of " + suitability);
}
}
然后我使用Respast Simphony将它们放入上下文(在网格的地理空间中):
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));
如果我是正确的,在下面的代码中,我创建了10个树对象,将它们添加到上下文中,然后创建了10个新的单独的树对象并将它们添加到ArrayList:
ArrayList<Tree> trees = new ArrayList<Tree>();
int treeCount = 10;
for (int i = 0; i < treeCount; i++) {
double suitability = Math.random();
int id = i;
context.add(new Tree(space, grid, suitability, id));
Tree tree;
tree = new Tree(space, grid, suitability, id);
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;
}
}
我的问题是:是否可以将10个树对象添加到上下文并将相同的对象添加到列表中?
答案 0 :(得分:1)
ArrayList<Tree> trees = new ArrayList<Tree>();
int treeCount = 10;
for (int i = 0; i < treeCount; i++) {
double suitability = Math.random();
int id = i;
// We create the Tree...
Tree tree = new Tree(space, grid, suitability, id);
// ... then add it to the context
context.add(tree);
// ... then add it to the list
trees.add(tree);
我不明白为什么它不起作用的原因。但我没有使用RepastSimphony的经验,所以我很可能错了:(