Sorting a subclass in Java

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

Or, in other words, will the Subclassmethod inherit compareToit by default Superclass, so you can blindly use it Arrays.sort(), knowing that they will be sorted as superclasses?

+5
source share
4 answers

- , . , A B, A , B, , B ( B).

, , , . compareTo .

? , Comparable<T> , . , -, , , compareTo , , , .

, , , - Square ColorSquare. compareTo :

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

... ColorSquare (, ). Java ColorSquare Comparable<ColorSquare> ( Comparable<Square>), , :

@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;
}

. - ColorSquare, ; .

, :

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!
+7

, compareTo, .


Effective Java TM

compareTo ( equals):

  • : x.compareTo(x) 0,
  • : x.compareTo(y) y.compareTo(x) 0,
  • : x.compareTo(y) > 0 y.compareTo(z) > 0; x.compareTo(z) > 0

... , compareTo, -

( yshavit)

, , . compareTo , superClass compareTo. ( , )

compareTo equals , , . . : 7, Java TM. , equals ( , compareTo), - -:

, . . 14, " ". , ColorPoint Point, ColorPoint Point ( 4)

+3

, compareTo , . , , , .

0
source

Yes, the behavior will be the same as you do not override the compareTo method, but then make sure that your subclass does not change any attributes in a way that could break the code break in the compareTo () method implemented in the superclass

0
source

All Articles