Hallo zusammen,
bei der Suche nach der Antwort meiner Frage, bin ich auf folgendes gestoßen:
My question is why cannot we just implement comparator, just like comparable and use a private function rather than inner class ?
Well (pretty much) the whole point of the Comparator interface is that an implementation of the interface is a separate class to the class of the objects being compared.
In theory you could do what you are suggesting, but the net result is counter-intuitive
In addition to being a bit counter-intuitive, your idea is limited in the sense that MyKey can only "provide" one comparator this way.
Frankly, if you are going to do this, it makes more sense to have MyKey implement Comparable<MyKey>.
Suppose that they had implemented String the way you proposed. Then this ...
... means sort case sensitive, but ...
... would mean sort case insensitive. Does that really strike you as a good idea? Really?
Dass, man bei obiger Implementierung von Comparator lediglich EINEN Vergleicher hat, das ist verständlich. Aber was ich nicht verstehe, ist der letzte Satz:
Viele Grüße aus Rheinland,
Eure Ratna
bei der Suche nach der Antwort meiner Frage, bin ich auf folgendes gestoßen:
My question is why cannot we just implement comparator, just like comparable and use a private function rather than inner class ?
Well (pretty much) the whole point of the Comparator interface is that an implementation of the interface is a separate class to the class of the objects being compared.
In theory you could do what you are suggesting, but the net result is counter-intuitive
Code:
public class MyKey implements Comparator<MyKey>{
private String field;
public boolean compare(MyKey m1, MyKey m2){
// We must ignore this.field! We are comparing m1 and m2 ...
return m1.field.compareTo(m2.field);
}
}
MyKey[] keys =...
Arrays.sort(keys,newMyKey());
// Note we have to pass an instance to provide the Comparator.
In addition to being a bit counter-intuitive, your idea is limited in the sense that MyKey can only "provide" one comparator this way.
Frankly, if you are going to do this, it makes more sense to have MyKey implement Comparable<MyKey>.
Suppose that they had implemented String the way you proposed. Then this ...
Code:
String[] strings =newString[]{"a","c","B"};
Arrays.sort(strings);
Code:
String[] strings =newString[]{"a","c","B"};
Arrays.sort(strings,"weasel");
Dass, man bei obiger Implementierung von Comparator lediglich EINEN Vergleicher hat, das ist verständlich. Aber was ich nicht verstehe, ist der letzte Satz:
Warum soll dies nicht im Sinne eines sauberen Codings sein? Es ist doch in Ordnung so zu programmieren, oder?... would mean sort case insensitive. Does that really strike you as a good idea? Really?
Viele Grüße aus Rheinland,
Eure Ratna