简体   繁体   中英

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 . ie 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

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

    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.

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);
    }

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;
}

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

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.

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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM