I founded this code on the web . Excuse-me if a ask here,but I haven’t only understand one thing. What does exactly return population2 – population1;?
It sorts the items by comparing every time each other (o1 and o2) , by taking the part after the colon without any eventual spaces (leadings and finals) , so the numbers, and sorting them by…?
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());
}
}
If i try to change, for example the code to:
return population1 - population2;
it orders the numbers as:
United States: 307006550
Russia: 141850000
Brazil: 193733800
India: 1155347700
China: 1331460000
Why?
The way comparisons are done is by comparing one value against another. However, because comparisons result in three possible answers instead of two, we need a convenient way to let the sorter know if the first element is less than, equal to, or greater than the second element. The easiest way to do this is to say that if element one is less than element two, return a negative number, if they are equal return a 0, and if the first element is greater, then return a positive number.
We can write this manually in code as
However, the sorter is only checking for negative and positive values, so the magnitude of the result does not matter, so long as a negative number means less than and a positive number means greater than. Now, because the two values we are comparing are numbers, and we want to sort them in descending order, we can just do
population1 - popultaion2. This will return a negative value if population1 is less than population2, 0 if they are the same, and a positive value if population1 is greater than population2. It is simply a convenience. If you want to opposite effect (sorting in ascending order), simply reverse the statement (as you have already shown).In regards to sleax’s latest comment, Java uses a modified Merge Sort that uses the information returned from the
compareTo(..)function. You can read about how Merge Sort works at Wikipedia.