Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing an object into a list doesn't work in Java?

Tags:

java

I'm having trouble retreiving data from a list. The values never seem to get stored, or the object is initialized? I made a class that stores some variables:

public class storage{
     public int a = 0;
     public int b = 0;
}

then I created another class which fills a, and b with some values and stores the object in a list

public class anotherclass{
      public List<storage> alldata = new ArrayList<storage>();

      public void filldata(){
            storage tmp = new storage();
            for (int i = 1; i <= 10; i++){
                 tmp.a = i;
                 tmp.b = i;
                 alldata.add(tmp);
            }
      }
}

but when I run filldata() in my main class, then try to get the object from the list a and b are still set at 0.

public static void main(String[] args){
    anotherclass obj = new anotherclass();
    obj.filldata()

    for (int i = 0; i <= obj.alldata.size() - 1; i++){
          System.out.println(obj.alldata.get(i).a)
          System.out.println(obj.alldata.get(i).b)
          //Outputs as all zeroes
    }

}

How could this be?

like image 719
rambodash Avatar asked Mar 26 '26 16:03

rambodash


1 Answers

Try to create the object every time. otherwise it use the same object. So only it wont add into your list.

            storage tmp = null;
            for (int i = 1; i <= 10; i++)
            {
                 tmp = new storage();
                 tmp.a = i;
                 tmp.b = i;
                 alldata.add(tmp);
            }

instead of

            storage tmp = new storage();
            for (int i = 1; i <= 10; i++)
            {
                 tmp.a = i;
                 tmp.b = i;
                 alldata.add(tmp);
            }
like image 90
newuser Avatar answered Apr 02 '26 21:04

newuser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!