6

我正在尝试为一个对象创建一个复制构造函数,其中一个参数是一个 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?

}
4

1 回答 1

17

我不确定这是否可以作为指向数组列表的“指针”,或者这是否会创建一个全新的数组列表对象

当您使用new时,它将创建一个全新的实例ArrayList(这是您所要求的)。但它也不会自动创建其元素的副本(我认为这是您正在寻找的)。这意味着,如果您在新 List 中更改了一个可变对象,那么它也会在原始 List 中更改,如果它仍然存在的话。这是因为 List 仅包含对其中 s 的引用(有点类但不完全是指针)Object,而不是实际Object的 s 本身。

例如:

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本身是可以独立修改的,但是当你使用构造函数接受另一个List时,两者都会包含对相同Person实例的引用,当这些对象在一个List中的状态发生变化时,它们也会在一个List中发生变化。其他(有点像指针)。

于 2012-06-27T23:29:39.523 回答