复制包含数组的对象

时间:2014-02-28 19:07:28

标签: java arrays object constructor

如何复制包含其他对象数组的对象?这是我的复制构造函数:

public university(university univ)    {
    String name1=univ.getname();
    int numOfPublications1=univ.getnumOfPublications(); 
    Department[] depts1 =new Department[numOfDepts];
    depts1=univ.getdepts();
}  

这不起作用,因为阵列不在那里。

5 个答案:

答案 0 :(得分:0)

您可以使用System.arraycopy()复制数组的内容。

class University {
  Department[] departments;

  University(University toCopy) {
    departments = new Department[toCopy.departments.length];
    System.arraycopy(toCopy.departments, 0, departments, 0, departments.length);
  }
}

答案 1 :(得分:0)

深度复制整个大学课程,包括Department数组中的每个元素,请更改此内容:

public university(university univ){
   ...
   Department[] depts1 =new Department[numOfDepts];
   depts1=univ.getdepts();
}

对此:

public university(university univ){
   ...
   depts1 =new Department[univ.depts1.length];
   for(int i = 0; i < univ.depts1.length; i++)  {
      depts[i] = new Department(univ.depts1[i]);
   }

}

这假设您的Department类也有一个复制构造函数。

请注意,我已更改

Department[] depts = ...

depts = ...

如果不这样做,那么新的depts数组将在构造函数的末尾停止存在。

答案 2 :(得分:0)

尝试这样做。

public university(university univ)    {
        String name1=univ.getname();
        int numOfPublications1=univ.getnumOfPublications(); 
        Department[] depts1 =new Department[numOfDepts];
        System.arrayCopy(univ.getdepts(),0,depts1,0,univ.getdepts().length);
//or this depts1 = Array.copyOf(univ.getdepts(),numOfDepts);
    }

答案 3 :(得分:0)

复制构造函数有很多问题,一般来说,克隆是首选,但如果你想在这里使用复制构造函数是这样的:

public University( University univ ){
    University univ_copy = new University();
    univ_copy.name = univ.getname();
    univ_copy.numOfPublications = univ.getnumOfPublications();
    univ_copy.departments = new Department[univ.numOfDepartments];
    System.arrayCopy( univ.departments, 0, univ_copy.departments, 0, univ.departments.length );
    return univ_copy;
}

您也可以逐个复制部门,而不是使用数组副本一步复制它们。关键是你需要为副本分配一个新数组,而不是重用univ中的现有数组,因为那时你就没有数组的副本,只是一个指向原始数组的指针。 / p>

答案 4 :(得分:0)

除了你没有遵循编码约定,使你的代码完全不可读之外,你应该复制(我假设你正在尝试做,因为你将 university 参数的实例提供给大学构造函数)部门而不是首先创建一系列部门,然后立即废弃并重新分配到参数的部门;

//Get departments from argument 
Department[] departments = univ.getdepts();

//Create your own local departments, if any
if (departments)
{
    this.departments = new Department[departments.length];

    //Copy, either cloned versions or references depending on what you want, for each and every cell in the argument university's department
    for (int i = 0; i < departments.length; i++)
        this.departments[i] = departments[i];
}