friends,
i am facing a problem i have phoneContacts list with name and phone numbers in it. i want to copy it in two different static lists so that i can use it to other activities. i am using following code but it displays me last list references in both while retrieving data any one guide me how can i 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.
To create a copy of an existing object in the vault, right-click the object of your choice and select Make Copy from the context menu. This command creates an entirely new object using the metadata and contents of the source object.
Object reference equality: when two object references point to the same object. Object value equality: when two separate objects happen to have the same values/state.
Both variables refer to the same object. Both strA and strB contain the same reference. So strA == strB evaluates to true. This is somewhat like giving your phone number to several people: each copy of your phone number is a reference to you, but there is only one you.
Yes, you are just making a reference to the object. You can clone the object if it implements Cloneable .
In this case you would need to make a deep copy of the list, i.e., a copy that doesn't copy references, but actually copies the object the references are pointing at.
Collections.copy
"copies all of the elements from one list into another". As usual with Java however, the elements of a list are not objects but references.
You could solve this by implementing Cloneable
(and using .clone()
) or by creating a custom "copy constructor" which takes a to-be-copied object as argument, and creates a new object based on the data of that argument. No matter which option you choose, you'll have to iterate over the list and perform the copy on each object.
Here's an example that uses the copy-constructor approach:
MyContacts.medicalContacts = new ArrayList();
for (Contact c: MyContacts.attackContacts)
medicalContacts.add(new Contact(c)); // add a copy of c.
Related question:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With