Mike, what you want is to sort objects which are naturally Comparable
(they implement the Comparable interface). Bag doesn't have that by
default, and it really ought to have it. ArrayList can be sorted
because it's a List, but Bag isn't strictly a List. Here's how you
can add it. Add following method to the Bag code:
/** Sorts the bag under the assumption that all objects stored
within are Comparable. */
public void sort()
Arrays.sort(objs, 0, numObjs);
This should sort them so that Comparable objects (like Double or
String) are arranged with lower-compared objects first in the list.
For example, if the Bag contains the doubles 9, 4, 10, it'll be
organized as 4, 9, 10. I'll put out a revised version of Bag with
this method and one or two others on SVN.
Now if you're storing doubles, I suggest you also consider using
DoubleBag instead, which holds an array of doubles rather than an
array of Objects. It has sort() already written for you.
On Jan 7, 2011, at 3:51 PM, Makowsky, Michael D. wrote:
> I am unclear, due to my limited java abilities, how to sort a bag of
> steppable agents by an attribute. Specifically. I have a bag of
> agents that I would like to sort by a value stored as a double
> (public double diff). The documentation states that I need to
> provide a comparator:
> public void sort(java.util.Comparator c)
> but am uncertain how to provide the java.lang.Double.compare method
> such that it sorts the bag of objects by the "diff" attribute, if in
> fact that is what I need to do.
> Thank you for your assistance.
> Michael D. Makowsky