Reputation: 49
I had to code my own compareTo()
-Method for a lexical order for Objects called Beer
, which compares the Beer
by beer type and beer name.
So here is my compareTo
Method:
@Override
public int compareTo(Beer b) {
String compareBeer1 = this.getBeerType() + this.getbName();
String compareBeer2 = b.getBeerType() + b.getbName();
for(int i = 0; i < compareBeer1.length(); i++) {
if(compareBeer1.charAt(i) > compareBeer2.charAt(i)) {
return compareBeer1.charAt(i) - compareBeer2.charAt(i);
} else if(compareBeer1.equals(compareBeer2)) {
return 0;
} else if((compareBeer1.charAt(i) == compareBeer2.charAt(i)) && (compareBeer1.length() - compareBeer2.length()) > 0){
return compareBeer1.length() - compareBeer2.length();
}
}
return -1;
}
So far so good, my problem here is now, that I have a Vector<Beer> filteredBeer
, which I have to sort also in lexical order. So for this, my code is:
Collections.sort(filteredBeer, new Comparator<Beer>() {
public int compare(Beer beer1, Beer beer2) {
return beer1.compareTo(beer2);
}
});
Still, I don't get the results I wish for, it doesn't compare the whole Vector
and sorts it. It does it only for the first two elements and that's it.
Can anyone help out? Or tell me, where my error here is?
Upvotes: 0
Views: 171
Reputation: 21134
Your compareTo
method is pretty strange.
What you should need is only this
@Override
public int compareTo(final Beer b) {
final var compareBeer1 = getBeerType().trim() + getName().trim();
final var compareBeer2 = b.getBeerType().trim() + b.getName().trim();
return compareBeer1.compareTo(compareBeer2);
}
Note that it can be enhanced for null-checks and other nice things.
Your beers will be sorted in ascending alphabetical order by type and name.
Tested with
final List<Beer> beers = new ArrayList<>();
beers.add(new Beer("tre", "nome2"));
beers.add(new Beer("due", "snome2"));
beers.add(new Beer("uno", "nome1"));
beers.add(new Beer("uno", "nome5"));
beers.add(new Beer("uno", "nome4"));
beers.add(new Beer("uno", "nome2"));
beers.add(new Beer("due", "nome1"));
Collections.sort(beers, Beer::compareTo);
Upvotes: 1
Reputation: 176
The compareTo depends on Beer's equals() method. looks like the equals() methods of Beer was not overridden correctly (or not overridden at all?) which in this case it rely on the Object's implementation...
Upvotes: 0