/** * Compares the given Chromosome to this Chromosome. This chromosome is considered to be "less * than" the given chromosome if it has a fewer number of genes or if any of its gene values * (alleles) are less than their corresponding gene values in the other chromosome. * * @param other the Chromosome against which to compare this chromosome * @return a negative number if this chromosome is "less than" the given chromosome, zero if they * are equal to each other, and a positive number if this chromosome is "greater than" the * given chromosome * @author Neil Rotstan * @author Klaus Meffert * @since 1.0 */ public int compareTo(Object other) { // First, if the other Chromosome is null, then this chromosome is // automatically the "greater" Chromosome. // --------------------------------------------------------------- if (other == null) { return 1; } int size = size(); IChromosome otherChromosome = (IChromosome) other; Gene[] otherGenes = otherChromosome.getGenes(); // If the other Chromosome doesn't have the same number of genes, // then whichever has more is the "greater" Chromosome. // -------------------------------------------------------------- if (otherChromosome.size() != size) { return size() - otherChromosome.size(); } // Next, compare the gene values (alleles) for differences. If // one of the genes is not equal, then we return the result of its // comparison. // --------------------------------------------------------------- for (int i = 0; i < size; i++) { int comparison = getGene(i).compareTo(otherGenes[i]); if (comparison != 0) { return comparison; } } // Compare current fitness value. // ------------------------------ if (m_fitnessValue != otherChromosome.getFitnessValueDirectly()) { FitnessEvaluator eval = getConfiguration().getFitnessEvaluator(); if (eval != null) { if (eval.isFitter(m_fitnessValue, otherChromosome.getFitnessValueDirectly())) { return 1; } else { return -1; } } else { // undetermined order, but unequal! // -------------------------------- return -1; } } if (m_compareAppData) { // Compare application data. // ------------------------- if (getApplicationData() == null) { if (otherChromosome.getApplicationData() != null) { return -1; } } else if (otherChromosome.getApplicationData() == null) { return 1; } else { if (getApplicationData() instanceof Comparable) { try { return ((Comparable) getApplicationData()) .compareTo(otherChromosome.getApplicationData()); } catch (ClassCastException cex) { /** @todo improve */ return -1; } } else { return getApplicationData() .getClass() .getName() .compareTo(otherChromosome.getApplicationData().getClass().getName()); } } } // Everything is equal. Return zero. // --------------------------------- return 0; }