Reputation: 29
I wanted to know what would be the best way to implement the comparator method following best practice?
I implemented one and someone else implemented the other.
Please any advice on which is more suitable would be great!
public class Product
{
public Product (String name, int weight) {
this.name = name;
this.weight = weight;
}
public static final Comparator<Product> BY_WEIGHT = new Comparator<Product>() {
public int compare(final Product weight1, final Product weight2) {
return weight1.weight - weight2.weight;
}
};
public String getName() {
return name;
}
public int getWeight() {
return weight;
}
}
or
public class Product {
private final String name;
private final int weight;
public Product (String name, int weight) {
this.name = name;
this.weight = weight;
}
public static final Comparator<Product> BY_WEIGHT = new Comparator<Product>(){
public int compare (final Product p1, final Product p2) {
return Integer.compare(p1.getWeight(), p2.getWeight());
}
};
public String getName() {
return name;
}
public int getWeight() {
return weight;
}
Upvotes: 1
Views: 92
Reputation: 5394
The second option, for reason already mentioned by @Eran.
This version uses built-in comparator:
public static final Comparator<Product> BY_WEIGHT =
Comparator.comparingInt(Product::getWeight);
Upvotes: 0
Reputation: 393936
The return weight1.weight - weight2.weight
implementation has a risk of numeric overflow, so it might misbehave for some inputs (though it's probably safe to assume a Product
's weight doesn't go anywhere near Integer.MAX_VALUE
or Integer.MIN_VALUE
, so that implementation will probably work fine) .
In general Integer.compare(p1.getWeight(), p2.getWeight())
is the better implementation, since it can't overflow (it returns (x < y) ? -1 : ((x == y) ? 0 : 1)
).
Upvotes: 4