使用ArrayList参数的拷贝构造函数

6
我正在尝试为一个对象制作复制构造函数,其中一个参数是ArrayList。
在创建ArrayList对象时,我想使用可以将集合作为参数传递的ArrayList构造函数,但我不确定这是否会将其作为"指针"传递给arraylist,还是会创建一个全新的arraylist对象。
以下是我的代码:
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?

}

它不会复制元素。(在我看来,这将是奇怪的。) - esej
2
你可以自己查看ArrayList的源代码。它已经包含在你的JDK中了。 - Edwin Dalorzo
1个回答

17
我不确定这是否可以作为指向数组列表的“指针”,或者是否会创建一个全新的数组列表对象。
当你使用 new 时,它将创建一个崭新的 ArrayList 实例(这就是你所请求的)。但它不会自动创建其元素的副本(我认为这就是你想要的)。这意味着,如果你在新列表中更改可变对象,原始列表中的该对象也会更改(如果原始列表仍然存在)。这是因为该列表只持有对其中的 Object 的引用(类似于但不完全是指针),而不是实际的 Object 本身。
例如:
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.
}

你可以看到这两个列表本身可以独立地进行修改,但当你使用接受另一个List的构造函数时,两个列表将包含对相同Person实例的引用,当这些对象在一个列表中的状态发生变化时,它们也会在另一个列表中发生变化(有点像指针)。


你认为在复制构造函数中创建一个全新列表的最佳实践是什么? 是实例化一个新的列表,迭代旧列表,并将新对象添加到新列表中吗? - ashishduh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接