我在网上创建了这段代码。打扰一下,如果在这里问,但我不只明白一件事。究竟是什么返回人口2 - 人口1; ? 它通过每次相互比较(o1和o2)来对项目进行排序,通过在冒号后面没有任何最终空格(前导和结尾)的部分,所以数字,并按...排序?
import java.util.Comparator;
import java.util.PriorityQueue;
public class Main {
public static void main(String[] args) {
PriorityQueue<String> queue = new PriorityQueue<String>(11,
new Comparator<String>() {
public int compare(String o1, String o2) {
int population1 = Integer.parseInt(o1.split(":")[1].trim());
int population2 = Integer.parseInt(o2.split(":")[1].trim());
return population2 - population1;
}
});
queue.add("United States: 307006550");
queue.add("Brazil: 193733800");
queue.offer("Russia: 141850000");
queue.offer("India: 1155347700");
queue.offer("China: 1331460000");
System.out.println("Countries in database: " + queue.size());
while (!queue.isEmpty()) {
System.out.println(queue.poll());
}
System.out.println("Countries in database: " + queue.size());
}
}
如果我尝试更改,例如将代码更改为:
return population1 - population2;
它将数字排序为:
United States: 307006550
Russia: 141850000
Brazil: 193733800
India: 1155347700
China: 1331460000
为什么?