Some additional points:
1) It is not necessary to convert power to a String
in order to compare it. You could do an integer based comparison:
int result = this.power - o.power;
if (result == 0) {
result = this.model.compareTo(o.model);
}
Note that this will produce a different sort order to the string-based comparison though (e.g. "200" > "10000" whereas 200 < 10000).
2) You could further optimise your compareTo
method by checking whether the object is being compared against itself:
public int compareTo(Product that) {
int ret;
if (this == that) { // Object is being compared against itself.
ret = 0;
} else {
// Do full comparison.
}
return ret;
}
3) From the Comparator Javadoc:
Caution should be exercised when using
a comparator capable of imposing an
ordering inconsistent with equals to
order a sorted set (or sorted map).
Your comparison method is only based on power and model whereas equality will be based on object identity unless you override the equals
method. Hence you may want to consider overriding equals
(and hashCode
) to make them consistent with compareTo
.