why does
List<Object> objectList; = some objects
List<Object> getList()
{
return objectList; //or return new List<Object>(objectList);
}
return a list with all items referenced to the original list’s items?
Thanks.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In the first case you just return a reference to the list.
In the second case (
new List<Object>(list)) the objects are not copied: only the references are copied! You have to clone each item in the collection to return a deep copy of the list.EDIT:
Iterate through your whole list and create a copy of each of your objects and put them into a new list.
See this for creating deep copies of custom objects. I would suggest not to use the interface
ICloneable. Make some research to learn why. 🙂