Adding an object to a collection returns "cannot be cast to java.lang.Comparable"

Asked

Viewed 65 times

2

The code is this:

public class Catalogo {
SortedSet<Produto> lProdutos = new TreeSet();

public void addProduto(int cod, String desc, float preco){
   try{
   Produto p = new Produto(cod, desc, preco);
   lProdutos.add(p);
   }
   catch (Exception e){
       System.out.println("Erro: " + e.getMessage());
   }
 }  
}

When executing, considering Cod = 5, desc = "x" and float = 5 fall on this exception:

catalogo. Product cannot be cast to java.lang.Comparable

What can it be?

1 answer

7


That’s exactly what the error message is saying, you didn’t implement the interface Comparable in your class Produto. For an object to be placed in a collection SortedSet this type needs to be able to deliver if an object of his is larger or smaller or equal to another object, after all this collection needs to be classified (Sorted) and the classification requires to know this characteristic.

So the error is in the class Produto and not in this code snippet, or with the data used, it should be something like (roughly speaking):

class Produto implements Comparable<Produto> {
    ...
    @Override
    public int compareTo(Produto outro) {
        return String.compare(this.nome, outro.nome);
    }
}

I put in the Github for future reference.

I’ve come up with a general alphabetical criterion for his general name that won’t be very good, but it might be what you want.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.