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