MyClass cannot be cast to java.lang.Comparable: ja

2019-01-15 18:57发布

I am doing a java project and I got this problem and don't know how to fix it.

The classes in my project (simplified):

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;

    }  
}

Then I try to sort an ArrayList of Stock so I create another class called CompareByValue

public class CompareByValue implements Comparator<Stock> {

    @Override
    public int compare(Stock stock1, Stock stock2) {

        return (stock1.getInventoryValue() - stock2.getInventoryValue());

    }

}

When I try to run the program, it gives the error:

Exception in thread "main" java.lang.ClassCastException: Stock cannot be cast to java.lang.Comparable

Anyone know what's wrong?

2条回答
欢心
2楼-- · 2019-01-15 19:19

It's because Stock isn't implementing Comparable. Either implement it:

public class Stock implements Comparable<Stock> {
    public int compareTo(Stock o) {
        // ...
    }
}

... Or pass an instance of CompareByValue as parameter to the sort() method:

Collections.sort(list, new CompareByValue());
查看更多
放荡不羁爱自由
3楼-- · 2019-01-15 19:24

only from above code, it looks fine. are you sure the exception from above code? if you just put Stock object into any sorted collection, you will see such exception and need to implement Comparable interface.

But for the case where just pass your custom Comparator, you don't need to make Stock to be a Comparable. it is same case like you give anonymous Comparator implementation.

set your comparator to sorted collection like TreeSet and then add the stock object into sorted collection, it should work without implemting Comparable interface.

查看更多
登录 后发表回答