Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding user defined objects to ArrayList in Java

Tags:

java

arraylist

I want to add a user defined type, like the one shown below, to an ArrayList.

import java.util.ArrayList;

class MyObj
{
    int iX;
}
public class testForLoopjava
{
    public static void main(String[] args)
    {
        MyObj ob1 = new MyObj();
        ArrayList<MyObj> al = new ArrayList<MyObj>();
        int a,b;
        for(int i =0;i<5;i++)
        {
            ob1.iX = i + 5;
            al.add(ob1);
        }
        for(int j=0;j<5;j++)
            System.out.println("iX: "+al.get(j).iX);
    }
}

When I try to print the above code, iX always prints 9. i.e. iX is updated by the last value in the list. What is the reason for this? Am I doing some basic mistake.?

Output:

iX: 9
iX: 9
iX: 9
iX: 9
iX: 9
like image 628
SyncMaster Avatar asked May 24 '26 09:05

SyncMaster


1 Answers

You're adding the same object to the list each time. You should use a fresh instance created within the loop.
e.g.-

    ArrayList<MyObj> al = new ArrayList<MyObj>();
    int a,b;
    for(int i =0;i<5;i++)
    {
        MyObj ob1 = new MyObj();
        ob1.iX = i + 5;
        al.add(ob1);
    }

Otherwise, your list will contain a list of references to the same instance and modifying that one instance affects every entry in that list.

This sort of issue is a strong argument for using immutable objects wherever possible. If you can, a good approach is to instantiate the iX field in the constructor and make it final thus not allowing it to change post-instantiation (check out the Java final keyword).

public class MyObj {
   private final int iX;
   public MyObj(int i) {
      iX = i; // iX is initialised here but can't be changed again
   }
}

This approach can yield a safer solution (wrt. the above) with the caveat that your objects can be changed post-instantiation. It sounds like a restrictive practice, but you'll be surprised to find many of your objects can be implemented in this fashion.

like image 169
Brian Agnew Avatar answered May 25 '26 23:05

Brian Agnew