在下面的代码中,我想了解 Collections.sort 函数在做什么。这是什么意思
Collections.sort(list, new Comparator() { a complete java function });
我理解这new Comparator()
意味着一个类对象,但是这里的功能块的目的是什么,以及我们在java中称之为什么。
谢谢。
/**
* Sorts/shuffles the given list according to the current sending queue
* mode. The list can contain either Message or Tuple<Message, Connection>
* objects. Other objects cause error.
* @param list The list to sort or shuffle
* @return The sorted/shuffled list
*/
@SuppressWarnings(value = "unchecked") /* ugly way to make this generic */
protected List sortByQueueMode(List list) {
switch (sendQueueMode) {
case Q_MODE_RANDOM:
Collections.shuffle(list, new Random(SimClock.getIntTime()));
break;
case Q_MODE_FIFO:
Collections.sort(list,
new Comparator() {
/** Compares two tuples by their messages' receiving time */
public int compare(Object o1, Object o2) {
double diff;
Message m1, m2;
if (o1 instanceof Tuple) {
m1 = ((Tuple<Message, Connection>)o1).getKey();
m2 = ((Tuple<Message, Connection>)o2).getKey();
}
else if (o1 instanceof Message) {
m1 = (Message)o1;
m2 = (Message)o2;
}
else {
throw new SimError("Invalid type of objects in " +
"the list");
}
diff = m1.getReceiveTime() - m2.getReceiveTime();
if (diff == 0) {
return 0;
}
return (diff < 0 ? -1 : 1);
}
});
break;
/* add more queue modes here */
default:
throw new SimError("Unknown queue mode " + sendQueueMode);
}
return list;
}
我终于让他理解了比较器。这个简单的例子会有所帮助:
Collections.sort(ls, new Comparator()
{
public int compare(Object o1, Object o2)
{
String sa = (String)o1;
String sb = (String)o2;
int v = sa.compareTo(sb);
return v;
// it can also return 0, and 1
}
}
);