【文章內(nèi)容簡(jiǎn)介】
covers all these cases 1314 Copyright 169。 2021 Pearson AddisonWesley. All rights reserved. The Comparable Interface ? The Comparable interface is in the package, and so is automatically available to any program ? It has only the following method heading that must be implemented: public int pareTo(Object other)。 ? It is the programmer39。s responsibility to follow the semantics of the Comparable interface when implementing it 1315 Copyright 169。 2021 Pearson AddisonWesley. All rights reserved. The Comparable Interface Semantics ? The method pareTo must return – A negative number if the calling object es before the parameter other – A zero if the calling object equals the parameter other – A positive number if the calling object es after the parameter other ? If the parameter other is not of the same type as the class being defined, then a ClassCastException should be thrown 1316 Copyright 169。 2021 Pearson AddisonWesley. All rights reserved. The Comparable Interface Semantics ? Almost any reasonable notion of es before is acceptable – In particular, all of the standard lessthan relations on numbers and lexicographic ordering on strings are suitable ? The relationship es after is just the reverse of es before 1317 Copyright 169。 2021 Pearson AddisonWesley. All rights reserved. The Comparable Interface Semantics ? Other orderings may be considered, as long as they are a total ordering ? Such an ordering must satisfy the following rules: – (Irreflexivity) For no object o does o e before o – (Trichotomy) For any two object o1 and o2, one and only one of the following holds true: o1 es before o2, o1 es after o2, or o1 equals o2 – (Transitivity) If o1 es before o2 and o2 es before o3, then o1 es before o3 ? The equals of the pareTo method semantics should coincide with the equals method if possible, but this is not absolutely required 1318 Copyright 169。 2021 Pearson AddisonWesley. All rights reserved. Using the Comparable Interface ? The following example reworks the SelectionSort class from Chapter 6 ? The new version, GeneralizedSelectionSort, includes a method that can sort any partially filled array whose base type implements the Comparable interface – It contains appropriate indexOfSmallest and interchange methods as well ? Note: Both the Double and String classes impleme