我正在尝试构建一个树形图,并为键类实现了我自己的Comparable接口,但我仍然得到一个“无法转换为可比较的”异常,我真的不明白为什么。这是我的代码的相关部分:
接口:
public interface Comparable<T> {
public int compareTo(T o);
}
密钥类:
public class PriorityBuy implements Comparable<PriorityBuy>{
protected double _priceDouble;
protected DollarValue _priceDollarValue = new DollarValue(_priceDouble);
protected Price _price = new Price(_priceDollarValue);
protected long _time;
public PriorityBuy(Price price, long time) {
this._price = price;
this._time = time;
}
public Price getPrice() {
return _price;
}
public long getTime() {
return _time;
}
/**
* The following provides a new choice of hash function for this class. The reason is that
* we need to create a new equals method to match the compareTo method, and we need to know
* that equal objects return equal hashCode.
*/
@Override
public int hashCode() {
return (int) (((_price.hashCode())*13)^(_time));
}
/**
* We re-implement the equals method to match our compareTo method, which depends on both price
* and on time.
*/
@Override
public boolean equals(Object o) {
if(! (o instanceof PriorityBuy)) {
return false;
}
PriorityBuy p = (PriorityBuy) o;
if(p.getPrice().getDollarValue().getValue() == _price.getDollarValue().getValue() && p.getTime() == _time) {
return true;
}
return false;
}
/**
* We are writing a compareTo method so that this class can implement Comparable<Priority>, which
* in turn allows any treemap constructed with Priority as the class of keys to order the tree
* according to the ordering defined by the compareTo method defined below, instead of using
* the "natural ordering" as it usually does.
*/
@Override
public int compareTo(PriorityBuy a) {
if(a.getPrice().getDollarValue().getValue() > this.getPrice().getDollarValue().getValue()) {
return -1;
}
else if(a.getPrice().getDollarValue().getValue() < this.getPrice().getDollarValue().getValue()) {
return 1;
}
else if(a.getTime() < this.getTime()) {
return -1;
}
else if(a.getTime() > this.getTime()) {
return 1;
}
else {
return 0;
}
}
}
我在树中添加元素的部分:
public void addToBuyBook(OrderBookMessage obm) throws Exception {
Order order = this.createOrder(obm);
TreeMap<PriorityBuy,Order> buyBookTree = _buyBook.get(obm.getTicker());
buyBookTree.put(order.getPriorityBuy(), order);
_buyBook.put(obm.getTicker(), buyBookTree);
this.addBuyOrder(obm.getOrderID(), obm.getTicker(), obm.getLimitPrice(), obm.getQuantity());
}
现在,当我使用测试来测试此代码时:
public void testAddToBuyBook() throws Exception {
OrderBookManager manager = new OrderBookManager();
OrderBookMessage obm1 = new OrderBookMessage("IBM");
OrderBookMessage obm2 = new OrderBookMessage("IBM");
manager.addToBuyBook(obm1);
manager.addToBuyBook(obm2);
}
然后它返回异常,即PriorityBuy无法解析为可比较。但似乎我已经构建了程序,以便这应该工作。所以......任何人都可以帮我看看它为什么不是吗?
答案 0 :(得分:3)
您无法创建自己的Comparable
界面;您必须使用内置java.lang.Comparable
。