What happens when comparator has a return value of 0?
Code:
private static final Comparator<Node> comparator = new Comparator<Node>() {
public int compare(Node one, Node two) {
if (one.id == two.id)
return 0;
if (one.f < two.f)
return -1;
if (one.f > two.f)
return 1;
return (one.id < two.id) ? -1 : 1;
}
};
Could anyone please explain each branch, how each element would be arranged in each case?
For example, when one.id == two.id, it returns 0; will "one" be put after or before "two"?
Thanks
Jack
Re: What happens when comparator has a return value of 0?
Read the API docs for the method.
how each element would be arranged in each case?
For example, when one.id == two.id, it returns 0; will "one" be put after or before "two"?
This method just returns a numeric value depending on whether one object is greater than, equal to, or less than the other. The method doesn't know about object order nor does it change the order of any objects, that is down to the calling object (assuming it wants to impose some sort of ordering).
For example: If you have a class that wants to order a collection of objects in descending order and it calls this method repeatedly to ascertain the order, the following would happen. If the method returns < 0 then object 1 will be placed after object 2. If the return value is 0 most implementations would not change the order of the objects but there is no rule which says they can't. And if it returns > 0 object 1 will be placed before object 2.
Bookmarks