Copy constructor with ArrayList parameter

I am trying to create a copy constructor for an object, and one of the parameters is an ArrayList.

when creating an ArrayList object, I meant to use the ArrayList constructor, in which you can pass the collection as a parameter, but I'm not sure if this will work as a "pointer" to an arraylist or if it will create a completely new arraylist object

This is the code that I have

public MyObject(MyObject other) { this.brands= other.brands; this.count = other.count; this.list = new ArrayList<Integer>(other.list); // will this create a new array list with no pointers to other.list elements? } 
+6
source share
1 answer

I'm not sure if this will work as a "pointer" to an arraylist or if it creates a new ararylist object

When you use new , it will create a brand spanking a new instance of ArrayList (this is what you requested). But it also does not automatically create copies of its elements (which, I think, is what you are looking for). This means that if you change the mutable object in the new list, it will also change in the original list if it is still around. This is because the List contains only links (kinda sorta, but not exactly pointers) to the Object , and not to the Object .

For instance:

 Person person = new Person("Rob"); // create a new Object List<Person> myList = new ArrayList<Person>(); myList.add(person); // Create another list accepting the first one List<Person> myList2 = new ArrayList<Person>(myList); for(Person p : myList2) { p.setName("John"); // Update mutable object in myList2 } person = new Person("Mary"); // stick another object into myList2 myList2.add(person); for(Person p : myList2) { System.out.println(p.getName()); // prints John and Mary as expected } for(Person p : myList) { System.out.println(p.getName()); // prints only one result, John. } 

So, you can see that the two lists themselves can be changed independently, but when you use a constructor that takes a different List , both will contain references to the same Person instances and when the state of these objects changes to one List, they will also change in another (sorta sorta is just like pointers).

+17
source

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


All Articles