javaandroidevents

Clone new objects to pass to ArrayList?


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

Solution

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