2

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"

Community
  • 1
  • 1
MTA
  • 739
  • 2
  • 9
  • 29
  • Which line are you getting the exception from? – Kayaman Nov 14 '13 at 08:33
  • @Kayaman according to his question - in `individualSortedSet.add(individual);` – Benjamin Gruenbaum Nov 14 '13 at 08:34
  • By any chance, do you have some other `Individual` class getting mixed up here? – Rohit Jain Nov 14 '13 at 08:39
  • I just realised that I was using a different SortedSet and I didnt add the 'new FitnessComparator()'. Intellij changes it to <~> and I didnt catch that! Thank you! its fixed - looking at another bug now :-/ – MTA Nov 14 '13 at 08:39
  • Sorry next time I will take a closer look at what line the exception is on.. – MTA Nov 14 '13 at 08:40
  • YOu can simplyfy compare method : `return individual2.getFitness() - individual2.getFitness()` – Areo Nov 14 '13 at 08:41
  • Are you really sure, you have used `new TreeSet(new FitnessComparator());` and there’s no `new TreeSet()` (without the Comparator) involved? – Holger Nov 14 '13 at 08:43
  • @Holger yes that was the problem! – MTA Nov 14 '13 at 08:49
  • I think I need to start naming my variables alot more clearly but I find it hard to think of good names – MTA Nov 14 '13 at 08:50

1 Answers1

1

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()); 
MTA
  • 739
  • 2
  • 9
  • 29