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
I wanted to implement either a Comparator or make Bid Comparable to compare two bids and order them by highest prices.
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. :-)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Attempt 1: Make Bid implement Comparable<Bid>:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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; | |
} |
- 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. :-)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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