return data[j].deepCopy();
Why do I have to return the deep copy of the object in the fetch method in array structure? Why can't I simply return the data[j]?
I would be very grateful if you also clarify me the concept of deep, shallow and cloning in java. I am beginner level programmer.
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
}
It appears to just be what the fetch method does.
You can always create an alternate method, to return the actual object.
And, on that note, it would be more useful to encapsulate a non deep-copying method.
Here is an example.