Saturday, 4 October 2014

Comparable or Comparator in Java?

I was writing some code recently where users can place bids on items.

I wanted to store the bids in a PriorityQueue to enable easy retrieval of the max bid on an item. 

Bid.java

public class Bid {
private final User user;
private final Item item;
private final int price; // in real life this would not be an int lol
public Bid(User user, Item item, int price) {
this.user = user;
this.item = item;
this.price = price;
}
public User getUser() {
return user;
}
public Item getItem() {
return item;
}
public int getPrice() {
return price;
}
view raw Bid.java hosted with ❤ by GitHub
I wanted to implement either a Comparator or make Bid Comparable to compare two bids and order them by highest prices.

Attempt 1: Make Bid implement Comparable<Bid>:


@Override
public int compareTo(Bid o) {
final int BEFORE = -1;
final int EQUAL = 0;
final int AFTER = 1;
if (this.getPrice() < o.getPrice()) return BEFORE;
if (this.getPrice() > o.getPrice()) return AFTER;
return EQUAL;
}
However:

- this doesn't really make sense because it only makes sense to compare two bids if they are associated with the same Item.
- given the current class structure, there is no way to handle this in the compareTo(Bid bid) method.

Therefore we should write a Comparator specifically for our use case to be passed into the Priority Queue. :-)

PriorityQueue queue = new PriorityQueue<Bid>(11, new BidComparator());

So in general it depends on whether the implementation of compare two is specific to the object or the usage. 

No comments:

Post a Comment

Scala with Cats: Answers to revision questions

I'm studying the 'Scala with Cats' book. I want the information to stick so I am applying a technique from 'Ultralearning...