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. :-)
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>:
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. :-)
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