How to create a copy of the same object with a different link?

friends

I ran into a problem. I have a list of phoneContacts with a name and phone numbers. I want to copy it in two different static lists so that I can use it for other actions. I use the following code, but it shows me the last list links, as when extracting data, someone will tell me how I can take separate copies of these two objects?

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 would be appreciated.

+6
source share
3 answers

In this case, you will need to make a deep copy of the list, i.e. a copy that does not copy the links, but actually copies the object that the links point to.

Collections.copy "copies all items from one list to another." As usual in Java, list items are not objects, but links.

This can be solved by implementing Cloneable (and using .clone() ) or by creating your own "copy constructor", which takes the object to be copied as an argument and creates a new object based on the data from this argument. No matter which option you choose, you will have to iterate over the list and make a copy for each object.

Here is an example that uses the copier constructor approach:

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

Related Question:

+10
source

List matching creates a new list object that still refers to the same element objects. To make a deep copy, your element object must be cloned, have a copy constructor, or some other way of duplicating it, and you need to make a copy in a loop, one after the other.

 for (Elem x: list1) { list2.add(copyOf(x)) } 
+1
source

Pass the object you want to copy and get the object you want,

 private Object copyObject(Object objSource) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(objSource); oos.flush(); oos.close(); bos.close(); byte[] byteData = bos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(byteData); try { objDest = new ObjectInputStream(bais).readObject(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } return objDest; } 

Passing an objDest object to a Desiered object

0
source

Source: https://habr.com/ru/post/889517/


All Articles