I’m trying to make a copy constructor for an object and one of the parameters is an ArrayList.
when creating the ArrayList object, I had in mind to use the ArrayList constructor where you can pass a collection as a parameter, but I’m not sure if this will work as a “pointer” to the arraylist or if this will create a whole new arraylist object
This is the code 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's elements?
}
When you use
new, it will create a brand spanking new instance ofArrayList(this is what you have asked). But it will not also automatically create copies of its elements (which I think is what you are looking for). What this means is, if you change a mutable object in the new List, it will also change in the original List, if it is still around. This is because the List only holds references (kinda sorta but not exactly pointers) to theObjects in them, not the actualObjects themselves.For example:
So you can see that the two Lists themselves can be modified independently, but when you use the constructor accepting another
List, both will contain references to the samePersoninstances, and when the state of these objects change in one List, they will also change in the other (kinda sorta just like pointers).