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

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

  

catalog.Product can not be cast to java.lang.Comparable

What can it be?

    
asked by anonymous 19.11.2018 / 16:40

1 answer

7

That's exactly what the error message is saying, you have not implemented the Comparable in your Produto class. In order for an object to be placed in a SortedSet collection, this type must be able to deliver if its object is greater or less than or equal to another object, after all this collection must be classified ( sorted ) and sorting requires knowing that feature.

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

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

I placed GitHub for future reference .

I invented a criterion, usually alphabetic of his general name will not be very good, but may be what you want.

    
19.11.2018 / 16:52