为什么我们必须在数组结构的 fetch 方法中返回对象的深层副本?

Why we have to return a deep copy of the object in the fetch method in array structure?

提问人:Coderey123 提问时间:10/5/2023 最后编辑:John KugelmanCoderey123 更新时间:10/5/2023 访问量:54

问:

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 数组 深度复制

评论

3赞 shmosel 10/5/2023
谁说你必须这样做?
0赞 Old Dog Programmer 10/5/2023
我们不知道什么是对象。我们不知道是否已经为 定义了 。由于返回类型是 和 是 的数组,因此不应生成编译器错误。但是,我们没有足够的信息来说明应该或不应该使用该方法。PersondeepCopy ( )PersonPersondataPersonreturn data[j]deepCopy ()
2赞 Slaw 10/5/2023
通常,返回副本是为了防止对原始对象进行修改。这是否是必需的完全取决于代码的设计/合同,由开发人员/设计人员决定。但是,如果对象是不可变的,那么返回副本是多余的。
0赞 Slaw 10/5/2023
另请参阅深拷贝和浅拷贝有什么区别?

答:

0赞 Reilas 10/5/2023 #1

"...为什么我必须在数组结构的 fetch 方法中返回对象的深拷贝?为什么我不能简单地返回数据[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

评论

1赞 rzwitserloot 10/5/2023
问题是:“为什么需要深度复制”。这根本没有回答所述问题。如果有的话,它似乎主张允许返回一个不深的副本,这是一个非常糟糕的主意,即一个使事情变得更糟的答案。
0赞 Reilas 10/5/2023
@rzwitserloot,是的,这就像“火腿之于仓鼠”。我差点摔倒,这太有趣了。
1赞 rzwitserloot 10/5/2023
这是一句相当普遍的说法,并得出正确的结论(即:每当出现“java 是否像 javascript 一样”时,假设答案是否定的,这往往会引导你得出正确的结论)。当然,这是一个评论。评论是与中心问题相关的注释和建议的正确位置。答案不是。