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

Posted by user2234225 on Stack Overflow See other posts from Stack Overflow or by user2234225
Published on 2013-10-31T21:18:38Z Indexed on 2013/10/31 21:54 UTC
Read the original article Hit count: 314

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?

© Stack Overflow or respective owner

Related posts about java

Related posts about sorting