Java – how to create a copy of the same object using different references?

Friends,

I'm facing a problem. I have a phonecontacts list, which contains names and phone numbers I want to copy it into two different static lists so that I can use it for other activities I'm using the following code, but it shows my last list reference when retrieving data. Does anyone guide me on how to copy these two objects separately?

MyContacts.attackContacts = new ArrayList(phoneContacts);
Collections.copy(MyContacts.attackContacts,phoneContacts);
MyContacts.attackContacts.get(0).setType("attack");

MyContacts.medicalContacts  = new ArrayList(phoneContacts);
Collections.copy(MyContacts.medicalContacts,phoneContacts);
MyContacts.medicalContacts.get(0).setType("medical");

System.out.println("attack" + MyContacts.attackContacts.get(0).getType() + " medical " + MyContacts.medicalContacts.get(0).getType());

// result "attack medical" "medical medical"
// it should show independent list results like "attack attack" "medical medical"

Any help will be greatly appreciated

Solution

In this case, you need to make a deep copy of the list, that is, you do not copy the copy of the reference, but actually copy the object to which the reference points

Collections. Copy "copies all elements from one list to another." But like Java, the elements of a list are not objects but references

You can solve this problem by implementing clonable (and using. Clone ()) or creating a custom copy constructor that takes the object to be copied as a parameter and creates a new object based on the data of the parameter Whichever option you choose, you must traverse the list and copy each object

This is an example of using the copy constructor method:

MyContacts.medicalContacts = new ArrayList();
for (Contact c: MyContacts.attackContacts)
    medicalContacts.add(new Contact(c));    // add a copy of c.

Related questions:

> What is the difference between a deep copy and a shallow copy?

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>