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
}
“...为什么我必须在数组结构的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