SyncMaster
SyncMaster

Reputation: 9936

Adding user defined objects to ArrayList in Java

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

Upvotes: 3

Views: 23483

Answers (7)

bhavesh
bhavesh

Reputation: 151

you are adding same object to list , because of this is giving same result. you have to create new instance every time. :)

Upvotes: 0

Mayur
Mayur

Reputation: 386

One more version using Object array:

package com.may.arrays;

import java.util.ArrayList;

public class AddObjectToArray {

    public static void main(String args[]){

        ArrayList<MyObject> l_list  = new ArrayList<MyObject>();
        MyObject l_myObj = new MyObject();  

        l_myObj.holder = new MyObject2[6];

        for(int i=0;i<5;i++){
            l_myObj.holder[i]   =   new MyObject2();    

            l_myObj.holder[i].value =   i+5;
            l_list.add(l_myObj);
        }

        for(int j=0;j<5;j++){
            System.out.println("value is: "+l_list.get(j).holder[j].value);
        }

    }
}
class   MyObject{
    MyObject2[] holder;
}
class   MyObject2{
    int value;
}

Upvotes: 0

Brian Agnew
Brian Agnew

Reputation: 272317

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.

Upvotes: 8

Nathan Q
Nathan Q

Reputation: 1902

You are changing the same object every time, so the last time in your loop it ill set ob1.iX = 4+5 (=9). You should create a new instance everytime, so put it in your loop:

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

Upvotes: 0

aishwarya
aishwarya

Reputation: 1986

thats because you are keeping just one reference to MyObj and all elements refer to it. try modifying the code as follows:

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

also, remove the ob1 definition outside of the loop.

Upvotes: 0

Fabian Barney
Fabian Barney

Reputation: 14549

You're adding the same object multiple times to the list. You have only one MyObj created and you only change the int value that object is holding.

Upvotes: 0

Shivan Dragon
Shivan Dragon

Reputation: 15219

That's because you're always putting the same instance (the same object) in your list.

try:

 public static void main(String[] args)
    {

        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);
        }
        for(int j=0;j<5;j++)
            System.out.println("iX: "+al.get(j).iX);
    }

Upvotes: 2

Related Questions