I am testing Comparator. Here I have my Class Item which has two field int price
and int comments
.
I override the compareTo function simply by sorting the price in ascending order then by comments.
Then I create my own Comparator by overriding the compare(Object o1, Object o2) function. It simply return the compareTo function from Item Class.
But as result it just does not work when I use my Comparator with Arrays.sort(array, new MyComparator())
Where did I go wrong?
class Item implements Comparable{
private double price;
private double comments;
public Item(double price, double comments){
this.comments = comments;
this.price = price;
}
@Override
public int compareTo(Object o) {
if (o instanceof Item){
Item item2 = (Item) o;
int priceCompare = Double.compare(this.price, item2.price);
if(priceCompare != 0) {
return priceCompare;
}
return Double.compare(this.comments, item2.comments);
}else{
throw new RuntimeException("Wrong compare Class");
}
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Items:{").append(" price: ").
append(price).append(" comments: ").append(comments).append(" }");
return stringBuilder.toString();
}
}
class MyComparator implements Comparator {
@Override
public int compare(Object o1, Object o2) {
System.out.println("asdasd");
if (o1 instanceof Item && o2 instanceof Item) {
Item item1 = (Item) o1;
Item item2 = (Item) o1;
return item1.compareTo(item2);
} else {
throw new RuntimeException("Wrong input type");
}
}
}
@Test
public void test3Comparator() {
Item[] items = new Item[]{new Item(65, 70),
new Item(45, 7),new Item(98, 89),
new Item(23, 56),new Item(78, 90)};
System.out.println(Arrays.toString(items));
Arrays.sort(items, new MyComparator());
System.out.println(Arrays.toString(items)); // Still shows the original order
}