2

I'm building an android app and I was trying to add objects to an ArrayList. I thought this would create a copy of the object in ArrayList and then I could reuse the object. I've realized this isn't the case and that ArryList was actually referencing the original object.

I'm not really sure how I'd use a loop to create new objects in the onCreate function so do I somehow need to clone the object and pass it to the ArrayList?

Anyway here's my code:

 public class Main extends Activity {
  private Item myItem = new Item();

  btnSave.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            alItems.add(myItem);
            arrayAdapter.notifyDataSetChanged();
Roman C
  • 49,761
  • 33
  • 66
  • 176
KingFu
  • 1,358
  • 5
  • 22
  • 42

2 Answers2

3

You can create a copy constructor in your Item class, and use it to create a copy of your object.

public class Item {
    private int field1;
    public Item() { }

    public Item(Item item) {
       this.field1 = item.field1;
    }
}

And add your object to list using: -

alItems.add(new Item(myItem));
Community
  • 1
  • 1
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
2

Make your Item implement Clonable then

public void onClick(View v) {
        alItems.add(myItem.clone());
        arrayAdapter.notifyDataSetChanged();
Roman C
  • 49,761
  • 33
  • 66
  • 176
  • 1
    A copy constructor is a better way to go than using `clone` method. Take a look at `Effective Java - Item # 11` – Rohit Jain Nov 05 '12 at 21:20
  • @RohitJain I'v used copy constructor in my environment but migrated to cloning and it had greatly simplified the implementation. – Roman C Nov 05 '12 at 21:25