Question

Please have a look at this:

I have a sortedset:

SortedSet<Individual> individualSortedSet = new TreeSet<Individual>(new FitnessComparator()); 

This is the comparator:

import java.util.Comparator;

public class FitnessComparator implements Comparator<Individual> {
    @Override
    public int compare(Individual individual1, Individual individual2) {
        if (individual1.getFitness() == individual2.getFitness())
            return 0;
        return (individual1.getFitness() > individual2.getFitness())? 1 : -1;
    }
}

The Individual class is just a data class.

When I try to add ad element to the sortedset:

individualSortedSet.add(individual);

I get the following runtime error:

Exception in thread "main" java.lang.ClassCastException: Individual cannot be cast to java.lang.Comparable

I really dont understand why. I have looked at the following links but I cannot make it work..

Why I'm not getting a class cast exception or some thing else when adding element to TreeSet

List to TreeSet conversion produces: "java.lang.ClassCastException: MyClass cannot be cast to java.lang.Comparable"

Was it helpful?

Solution

There was a different sortedList in the code that was defined as follows:

SortedSet<Individual> individualSortedSet = new TreeSet<Individual>(); 

I didnt see that I have declared it again.. This is the correct declaration:

SortedSet<Individual> individualSortedSet = new TreeSet<Individual>(new FitnessComparator()); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top