我正在做一个java项目,我得到了这个问题,不知道如何解决它。MyClass不能转换为java.lang.Comparable:java.lang.ClassCastException
在我的项目中的类(简体):
public class Item {
private String itemID;
private Integer price;
public Integer getPrice() {
return this.price;
}
}
public class Store {
private String storeID;
private String address;
}
public class Stock {
private Item item;
private Store store;
private Integer itemCount;
public Integer getInventoryValue() {
return this.item.getPrice() * this.itemCount;
}
}
然后我尝试整理股票的ArrayList
所以我创建另一个类称为CompareByValue
public class CompareByValue implements Comparator<Stock> {
@Override
public int compare(Stock stock1, Stock stock2) {
return (stock1.getInventoryValue() - stock2.getInventoryValue());
}
}
当我尝试运行该程序,它会给出错误:
Exception in thread "main" java.lang.ClassCastException: Stock cannot be cast to java.lang.Comparable
任何人都知道什么是错的?
你如何运行程序,特别是在你对列表进行排序的地方? –