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

68 Views Asked by At
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
}
1

There are 1 best solutions below

3
Reilas On

"... 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]? ..."

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.

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