title: Adding user defined objects to ArrayList in Java
body: <p>I want to add a user defined type, like the one shown below, to an <code>ArrayList</code>. </p>
  
  <pre><code>import java.util.ArrayList;
  
  class MyObj
  {
      int iX;
  }
  public class testForLoopjava
  {
      public static void main(String[] args)
      {
          MyObj ob1 = new MyObj();
          ArrayList&lt;MyObj&gt; al = new ArrayList&lt;MyObj&gt;();
          int a,b;
          for(int i =0;i&lt;5;i++)
          {
              ob1.iX = i + 5;
              al.add(ob1);
          }
          for(int j=0;j&lt;5;j++)
              System.out.println("iX: "+al.get(j).iX);
      }
  }
  </code></pre>
  
  <p>When I try to print the above code, <code>iX</code> always prints <code>9</code>. i.e. <code>iX</code> is updated by the last value in the list. What is the reason for this? Am I doing some basic mistake.?</p>
  
  <p>Output:</p>
  
  <pre><code>iX: 9
  iX: 9
  iX: 9
  iX: 9
  iX: 9
  </code></pre>