Consider the following compareTo method, implementing the Comparable<T>
interface.:
@Override
public int compareTo(MyObject o)
{
if (o.value.equals(value)
return 0;
return 1;
}
Apparantly, the programmer implemented the compareTo as if it was equals(). Obviously a mistake. I would expect this to cause Collections.sort() to crash, but it doesn't. Instead it will just give an arbitrairy result: the sorted result is dependant on the initial ordering.
public class MyObject implements Comparable<MyObject>
{
public static void main(String[] args)
{
List<MyObject> objects =
Arrays.asList(new MyObject[] {
new MyObject(1), new MyObject(2), new MyObject(3)
});
Collections.sort(objects);
System.out.println(objects);
List<MyObject> objects2 =
Arrays.asList(new MyObject[] {
new MyObject(3), new MyObject(1), new MyObject(2)
});
Collections.sort(objects2);
System.out.println(objects2);
}
public int value;
public MyObject(int value)
{
this.value = value;
}
@Override
public int compareTo(MyObject o)
{
if (value == o.value)
return 0;
return 1;
}
public String toString()
{
return "" + value;
}
}
Result:
[3, 2, 1]
[2, 1, 3]
Can we come up with a use case for this curious implementation of the compareTo, or is it always invalid. And in case of the latter, should it throw an exception, or perhaps not even compile?
There's no reason for it to crash or throw an exception.
You're required to fulfil the contract when you implement the method, but if you don't, it just means that you'll get arbitrary results from anything that relies on it. Nothing is going to go out of its way to check the correctness of your implementation, because that would just slow everything down.
A sorting algorithm's efficiency is defined in terms of the number of comparisons it makes. That means that it's not going to add in extra comparisons just to check that your implementation is consistent, any more than a HashMap
is going to call .hashcode()
on everything twice just to check it gives the same result both times.
If it happens to spot a problem during the course of sorting, then it might throw an exception; but don't rely on it.