1

I have an arraylist of type "Person" entity and I wanted to get the separate instance of a object of type Person from arraylist. But when I do the same and update a property of a entity, the entity in the arraylist gets updated. Thus in all maintaining the same reference in memory to the object. I wanted to create a separate memory reference.In below code personEntity at postion 0 and 1 both get cardType "add".

 Person personEntity=personArrayList.get(0);
 personEntity.setCardType("add");
 personArrayList.add(1,personEntity);
Android QA
  • 31
  • 3
  • You need to create a new Person (using the new keyword) and somehow copy all the attributes of your original person into it. There is no straightforward way. Can you add the code of the Person class? – Bentaye Jun 25 '19 at 12:11
  • 2
    See https://www.baeldung.com/java-deep-copy – Bentaye Jun 25 '19 at 12:14
  • If you are using Spring, then you may use BeanUtils.copyproperties(src,trgt,ignoreProp); function for shortening your code. You have to create a new instance separately and can use that 2nd instance as target and 1st instance as source in this function. – Ashish Sharma Jun 25 '19 at 12:30
  • Bentaye your answer helped me. Thanks a lot was stuck in for much time – Android QA Jun 25 '19 at 12:39

3 Answers3

0

Write a copy constructor for Person and do this:

 Person personEntity = new Person(personArrayList.get(0));

Your copy constructor will depend on the structure of your Person class. The copy constructor will use the values of properties in personArrayList.get(0) to initialize a new instance of Person.

nicomp
  • 4,344
  • 4
  • 27
  • 60
0

What if you try to clone it?

 Person personEntity=personArrayList.get(0).clone();
 personEntity.setCardType("add");
 personArrayList.add(1,personEntity);

Or even better define a constructor in Person that you create using a Person as parameter then you can do

 Person personEntity= Person.from(personArrayList.get(0));
 personEntity.setCardType("add");
 personArrayList.add(1,personEntity);
0

You should implement Cloneable interface.

https://docs.oracle.com/javase/7/docs/api/java/lang/Cloneable.html

Object.clone() supports only shallow copying but we will need to override it if we need deep cloning. Then, you just need to create this method:

@Override
public Test clone(){
    try {
        return (Test)super.clone();
    } catch (CloneNotSupportedException e) {
        e.printStackTrace();
        return null;
    }

}

That's because Object.clone() is protected. You can get more info at

https://www.javatpoint.com/object-cloning

Turvo
  • 211
  • 2
  • 7
  • when clone is used and any attribute is updated the same gets reflected into parent one – Android QA Jun 25 '19 at 12:35
  • If it is a primitive type, it doesn't get reflected. If it isn't, you must implement your own clone(). As I said, "Object.clone() supports only shallow copying but we will need to override it if we need deep cloning. " – Turvo Jun 25 '19 at 12:51