gpt4 book ai didi

java函数定义与对象创建

转载 作者:行者123 更新时间:2023-12-01 19:45:13 24 4
gpt4 key购买 nike

在下面的代码中,我想了解 Collections.sort 函数在做什么。这意味着什么

Collections.sort(list, new Comparator() { a complete java function });

我明白new Comparator()意味着一个类对象,但是这里的功能 block 的用途是什么,以及我们在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
}
}
);

最佳答案

这就是 anonymous inner class .
它用于将函数作为参数传递,因为 Java 不支持函数指针。

关于java函数定义与对象创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10670476/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com