Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 371
user2234225 Avatar asked Oct 31 '13 21:10

user2234225


People also ask

How do I resolve Java Lang ClassCastException error?

To prevent the ClassCastException exception, one should be careful when casting objects to a specific class or interface and ensure that the target type is a child of the source type, and that the actual object is an instance of that type.

What is Java Lang ClassCastException?

ClassCastException is a runtime exception raised in Java when we try to improperly cast a class from one type to another. It's thrown to indicate that the code has attempted to cast an object to a related class, but of which it is not an instance.

Why do we get ClassCastException in TreeSet?

This error is thrown by TreeSet because TreeSet is used to store elements in sorted order and if the specified element cannot be compared with the elements currently in the set then TreeSet won't be able to store elements in sorted order and hence, TreeSet throws class cast exception.

What is Java comparable interface?

The Java Comparable interface, java. lang. Comparable , represents an object which can be compared to other objects. For instance, numbers can be compared, strings can be compared using alphabetical comparison etc. Several of the built-in classes in Java implements the Java Comparable interface.


1 Answers

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());
like image 164
Óscar López Avatar answered Sep 25 '22 22:09

Óscar López