Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a subclass in Java

Suppose a Superclass implements Comparable<Superclass>, such that Arrays.sort(ArrayOfSuperInstances); uses this compareTo(Superclass other) method to sort. Does this guarantee that an array of instances of Subclass extends Superclass will sort in the same way using Arrays.sort(ArrayOfSubInstances); ? (Assuming the compareTo is not overloaded in the subclass definition)

Or in other words, will Subclass by default inherit the compareTo method of its Superclass , so that one can blindly use Arrays.sort() knowing they will be sorted as superclasses would be?

like image 361
propaganda Avatar asked Aug 13 '12 05:08

propaganda


1 Answers

Yes -- that is the whole principle behind polymporphism, and specifically the Liskov substitution principle. Basically, if A is a subclass of B, then you should be able to use A anywhere you'd be able to use B, and it should essentially act the same as any other instance of B (or other subclasses of B).

So, not only will it happen, but it's almost always what you want to happen. It's usually wrong to compareTo in the subclass.

Why? Well, part of the Comparable<T> contract is that comparison is transitive. Since your superclass will presumably not know what its subclasses are doing, if a subclass overrides compareTo in such a way that it gives an answer different than its superclass, it breaks the contract.

So for instance, let's say you have something like a Square and a ColorSquare. Square's compareTo compares the two squares' sizes:

@Override
public int compareTo(Square other) {
    return this.len - other.len;
}

...while ColorSquare also adds a comparison for color (let's assume colors are Comparable). Java won't let you have ColorSquare implement Comparable<ColorSquare> (since its superclass already implements Comparable<Square>), but you can use reflection to get around this:

@Override
public int compareTo(Square other) {
    int cmp = super.compareTo(other);
    // don't do this!
    if (cmp == 0 && (other instanceof ColorSquare)) {
        ColorSquare otherColor = (ColorSquare) other;
        cmp = color.compareTo(otherColor.color);
    }
    return cmp;
}

This looks innocent enough at first. If both shapes are ColorSquare, they'll compare on length and color; otherwise, they'll only compare on length.

But what if you have:

Square a = ...
ColorSquare b = ...
ColorSquare c = ...

assert a.compareTo(b) == 0;  // assume this and the other asserts succeed
assert a.compareTo(c) == 0;
// transitivity implies that b.compareTo(c) is also 0, but maybe
// they have the same lengths but different color!
assert b.compareTo(c) == 1; // contract is broken!
like image 132
yshavit Avatar answered Sep 28 '22 19:09

yshavit