为什么我们要在数组结构的fetch方法中返回对象的深拷贝?

问题描述 投票:0回答:1
return data[j].deepCopy(); 

为什么数组结构的fetch方法中必须返回对象的深拷贝?为什么我不能简单地返回数据[j]?

如果您也向我澄清java中的深、浅和克隆的概念,我将非常感激。我是初级程序员。

package objectsortapp;

public class SortedArray {
    private Person[] data; // reference to array data
    private int next; // place where next item will be inserted
    
    public SortedArray(int max) // constructor
    {
        data = new Person[max]; // create the array with max elements
        next = 0; // array is empty
    } // end constructor
    
    public Person fetch(String last) // find a specific person based on last name
    {
        int j=0;
        for(j=0; j<next; j++) // iterate through the loop to find it
        {
            if((data[j].getLast()).equalsIgnoreCase(last)) // compare the entry in the array to the parameter value
                break;
        }
        
        if(j==next)
        {
            return null; // person with that last name was not found
        }
        else
        {
            return data[j].deepCopy(); // person is found, so return a deep copy of their node
        }
    } // end fetch
}
java arrays deep-copy
1个回答
0
投票

“...为什么我必须在数组结构的fetch方法中返回对象的深拷贝?为什么不能简单地返回data[j]?...”

这似乎就是 fetch 方法所做的事情。

您始终可以创建替代方法来返回实际对象。

而且,在这一点上,封装一个非深度复制方法会更有用。

这是一个例子。

public Person fetchDeepCopy(String last) {
    return fetch(last).deepCopy();
}
    
public Person fetch(String last) // find a specific person based on last name
{
    int j=0;
    for(j=0; j<next; j++) // iterate through the loop to find it
    {
        if((data[j].getLast()).equalsIgnoreCase(last)) // compare the entry in the array to the parameter value
            break;
    }

    if(j==next)
    {
        return null; // person with that last name was not found
    }
    else
    {
        return data[j]; // person is found, so return a deep copy of their node
    }
} // end fetch
© www.soinside.com 2019 - 2024. All rights reserved.