我正在尝试为对象创建一个复制构造函数,其中一个参数是一个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?
}
Run Code Online (Sandbox Code Playgroud)
Jes*_*run 17
我不确定这是否可以作为arraylist的"指针",或者如果这将创建一个全新的arraylist对象
当你使用时new,它会创建一个品牌打屁股的新实例ArrayList(这就是你所要求的).但它也不会自动创建其元素的副本(我认为这是你正在寻找的).这意味着,如果您更改新列表中的可变对象,它也将在原始列表中更改,如果它仍然存在.这是因为List只保存对Object它们中的s的引用(有点但不完全是指针),而不是实际的Objects本身.
例如:
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.
}
Run Code Online (Sandbox Code Playgroud)
所以你可以看到两个Lists本身可以独立修改,但是当你使用构造函数接受另一个时List,它们都将包含对同一个Person实例的引用,当这些对象的状态在一个List中发生变化时,它们也会在其他(有点像指针).
| 归档时间: |
|
| 查看次数: |
7479 次 |
| 最近记录: |