提问人:Coderey123 提问时间:10/5/2023 最后编辑:John KugelmanCoderey123 更新时间:10/5/2023 访问量:54
为什么我们必须在数组结构的 fetch 方法中返回对象的深层副本?
Why we have to return a deep copy of the object in the fetch method in array structure?
问:
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
}
答:
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 一样”时,假设答案是否定的,这往往会引导你得出正确的结论)。当然,这是一个评论。评论是与中心问题相关的注释和建议的正确位置。答案不是。
评论
Person
deepCopy ( )
Person
Person
data
Person
return data[j]
deepCopy ()