复制包含数组的对象 [英] Copy an object containing an array

查看:205
本文介绍了复制包含数组的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I copy an object containing an array of other objects? Here is my copy constructor:

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


$ b $ p

这不工作,因为数组不存在。

This is not working because the array is not there.

推荐答案

除了你不遵循编码惯例,使你的代码完全不可读,你应该复制试图这样做,因为您向大学构造函数提供了大学参数的实例)部门,而不是首先创建一个部门数组,然后立即报废并重新分配给参数的部门;

Besides that you do not follow coding conventions, making your code completely unreadable, you should copy (which I assume you're trying to do, since you feed an instance of university argument to the university constructor) the departments instead of first creating an array of departments that you then immediately scrap and reassign the to argument's departments;

//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];
}

这篇关于复制包含数组的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆