Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy am I getting a class cast exception if I have implemented comparator?
    primarykey
    data
    text
    <p>Please have a look at this:</p> <p>I have a sortedset:</p> <pre><code>SortedSet&lt;Individual&gt; individualSortedSet = new TreeSet&lt;Individual&gt;(new FitnessComparator()); </code></pre> <p>This is the comparator:</p> <pre><code>import java.util.Comparator; public class FitnessComparator implements Comparator&lt;Individual&gt; { @Override public int compare(Individual individual1, Individual individual2) { if (individual1.getFitness() == individual2.getFitness()) return 0; return (individual1.getFitness() &gt; individual2.getFitness())? 1 : -1; } } </code></pre> <p>The Individual class is just a data class.</p> <p>When I try to add ad element to the sortedset:</p> <pre><code>individualSortedSet.add(individual); </code></pre> <p>I get the following runtime error:</p> <pre><code>Exception in thread "main" java.lang.ClassCastException: Individual cannot be cast to java.lang.Comparable </code></pre> <p>I really dont understand why. I have looked at the following links but I cannot make it work..</p> <p><a href="https://stackoverflow.com/questions/12001946/why-im-not-getting-a-class-cast-exception-or-some-thing-else-when-adding-elemen">Why I&#39;m not getting a class cast exception or some thing else when adding element to TreeSet</a></p> <p><a href="https://stackoverflow.com/questions/2504803/list-to-treeset-conversion-produces-java-lang-classcastexception-myclass-cann">List to TreeSet conversion produces: &quot;java.lang.ClassCastException: MyClass cannot be cast to java.lang.Comparable&quot;</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload