2

Take the Jzombie model for example, if I want to query all humans with energy equal to 5 and put them in a list I would be have the following codes:

List<Human> human_list = ArrayList<Human>();
Query<Object> query = new PropertyEquals<Object>(context, "energy", 5);
for (Object o : query.query()) {
    Human h = (Human)o;
    human_list.add(h);
}

However, the order of human in human_list is random and different between different simulation runs. This cause a problem of inconsistent result like below:

run-1:
[human_2, human_4, human_3, human_5, human_1] 

run-2:
[human_1, human_3, human_4, human_2, human_1] 

run-3:
[human_5, human_1, human_3, human_5, human_2] 

I actually want to query the human with engergy == 5 and sort them by their id like:

[human_1, human_2, human_3, human_4, human_5]

so that when I perform some further actions and I can always get the consistent result.

Jack
  • 1,131
  • 1
  • 8
  • 17

1 Answers1

3

The object order from queries is not guaranteed, however the objects would always be the same assuming that the model is otherwise fully deterministic. Therefore, you will need to sort the query result list using Collections.sort(). Sorting the array requires that the contained objects can be compared to determine the ordering. For arrays that contain simple types like numbers or strings, this is simply a matter of calling Collections.sort() on the array. Since you'd like to compare agents, you need to have the agent class implement comparable like:

public class Human implements Comparable<Human>{

and then provide an implementation of the compareTo() method, such as the following which compares agents based on their String name:

@Override public int compareTo(Human other) { return this.name.compareTo(other.name); }

Sorting the human list is simply via:

Collections.sort(human_list);

If you specify the Human agent names like Human-1, Human-2, etc, you might see output that looks something like:

[Human-18, Human-3, Human-7, Human-86, Human-92]

And you will see the same order every time. Since in this example we are comparing Strings, the order might not be they way we are expecting. String comparison looks at the first digit after the dash, so that "Human-18" is ordered before "Human-3", since "1" < "3" at this character position. To sort in a more logical fashion, we can compare Human agents with an integer ID. The new compareTo would look like:

@Override public int compareTo(Human other) { return this.id - other.id; }

This prints the Human order as follows:

[Human-3, Human-7, Human-18, Human-86, Human-92]

Eric Tatara
  • 660
  • 3
  • 12