MyClass cannot be used for java.lang.Comparable: java.lang.ClassCastException

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

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 the 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 an error:

Exception in thread "main" java.lang.ClassCastException: stocks cannot be added to java.lang.Comparable

Does anyone know what happened?

+8
java sorting exception comparable classcastexception
source share
2 answers

This is because Stock does not implement Comparable . Or do it:

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

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

 Collections.sort(list, new CompareByValue()); 
+12
source share

just from the code above, it looks great. Are you sure the exception to the code is above? if you just placed the Stock object in any sorted collection, you will see such an exception and must implement the Comparable interface.

But for the case when you just go through your custom comparator, you do not need to make the goods comparable. this is the same case as the anonymous comparator implementation.

set your comparator to a sorted collection, for example TreeSet, and then add the stock object to the sorted collection, it should work without using the Comparable interface.

0
source share

All Articles