0

I have a main method

  import java.util.*;
  public class teststate
  {
      public static void main(String[] args) throws Exception
       {
   
      StackArrayList<Integer> s=new StackArrayList<Integer>();
      state[] array=new state[4];
      for(int i=0;i<3;++i)
      {
         state s1=new state();
         s1.col=i;
         array[i]=s1;
         //s.push(i);
      }
      
      for(int i=0;i<array.length;++i)
      {
         state test=array[i];
         
         System.out.println(test.col);
      }
   }
}

And i also have a class: state

  public class state
  {
     public static String name;
     public static  int col;
     
     
     public state()
     {
        this.name="";
        this.col=0;
     }
     public state(String name, int col)
     {
        this.name=name;
        this.col=col;
     }//end non defualt
  
  }//end inner class

I want the output to be 0,1,2. But the output prints out 2,2,2. I know this happens becuase it is the same object reference being found when I try to print. So what can I change to get a different object to be added to my array every time in the for loop?

Progman
  • 16,827
  • 6
  • 33
  • 48
  • 2
    Remove both `static`(s) from `public static String name;` and `public static int col;` Consider `array[i] = new state("", i);` and that it should be called `State` – Elliott Frisch Sep 11 '22 at 01:36

0 Answers0