Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instance variables are the same in each object initialization

I'm making a genetic algorithm that deals with evolving an array of chars into "Hello World". The problem is whenever I initialize a Chromosome object and call the generateChromosome method, all the chromosomes of "test" population remains the same?

public class Chromosome{
   private static int defaultLength = 11;
   private static char []genes = new char[defaultLength]; <--- this remains the same for each object :/


   //Generates a random char chromosome
   public void generateChromosome(){
      char []newGene =  new char[defaultLength];
      for(int x = 0; x<size(); x++){
         char gene = (char)(32+Math.round(96*Math.random()));
         newGene[x] = gene;

      }
      genes = newGene;

   }

   //Returns a specific gene in the chromosome
   public char getGene(int index){
     return genes[index];
   }

   public char[] getChromosome(){
      return genes;
   }

   public void setGene(char value, int index){

   genes[index] = value;

   }

   public static  void setDefaultLength(int amount){
      defaultLength = amount;
   }

   public static int getDefaultLength(){
      return defaultLength;
   }

   public int size(){
      return genes.length;
   }

   @Override
   public String toString(){
      String geneString = "";
      for(int x= 0; x<genes.length; x++){
         geneString += genes[x];
      }
      return geneString;
   }
}
like image 703
monsterbasher Avatar asked Jan 10 '23 04:01

monsterbasher


1 Answers

That's because your variables are static, i.e. class variables. They will be the same in each instantiation of your class.

If you want an instance variable, remove the static keyword.

like image 179
ktm5124 Avatar answered Jan 29 '23 04:01

ktm5124