-1

I wanted to remove the static key word from my code. But in the fitness function method it gives me an error. Is the static key-word is essential in the fitness function method?

Here is the code which gives me an error.

public void optimize()
{
    long l1 = System.currentTimeMillis();
    final Factory<Genotype<IntegerGene>> gtf = Genotype.of(IntegerChromosome.of(0, all.length - 1, LEN));
    final Engine<IntegerGene, Integer> engine = Engine.builder(eval, gtf).populationSize(1000).build();
    System.out.println("engine.getPopulationSize() = " + engine.getPopulationSize());
    final EvolutionResult<IntegerGene, Integer> result = engine.stream().limit(500).collect(EvolutionResult.toBestEvolutionResult());
    Genotype<IntegerGene> genotype = result.getBestPhenotype().getGenotype();
    System.out.println("result = " + genotype);
    System.out.println("result.getBestPhenotype().getFitness() = " + result.getBestPhenotype().getFitness());
    System.out.println("Time taken : " + (System.currentTimeMillis() - l1));
}

Can the fitness function could be non-static or it should be always static? Can someone help?

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
  • Static functions should be avoided as much as possible. They have their uses, but in general they are not needed. The Java compiler has no knowledge of the domain you are in, so it does not differentiate on that. – M. le Rutte Apr 21 '18 at 05:52
  • But why the error is coming as I changed it to a non-static method? – Maleesha Perera Apr 21 '18 at 06:04
  • 1
    What error are you getting? – khelwood Apr 21 '18 at 06:14
  • 1
    @M.leRutte Why should static methods/functions avoided as much as possible? – Progman Apr 21 '18 at 09:48
  • Because static methods can only refer to a static ('application wide') context. – M. le Rutte Apr 21 '18 at 16:57
  • @M.leRutte Indeed, that is the point of static methods but why would one avoid them as much as possible. The case you give is a use case not a 'downside' or problem. – tom Apr 23 '18 at 08:14

1 Answers1

0

I'm going to guess that EvolutionResult.toBestEvolutionResult() is the fitness function. Please correct me if it isn't.

The way you are calling it, it must be a static method, as the EvolutionResult part refers to a class, not an instance of a class.

You could instead say:

EvolutionResult evolutionResult = new EvolutionResult();
...
    final EvolutionResult<IntegerGene, Integer> result = 
          engine.stream()
                .limit(500)
                .collect(evolutionResult.toBestEvolutionResult());

Then you've created an instance of a class, and can call methods on it, so toBestEvolutionResult() no longer needs to be static.

tgdavies
  • 10,307
  • 4
  • 35
  • 40