To illustrate my concern, I will use the following incomplete Test Class:
import java.util.ArrayList;
public class Test
{
private int[] myArray = {1,2,3,4,5};
private ArrayList<Integer> myArrayList = new ArrayList<Integer>();
public int[] getMyArray()
{
int[] temp = new int[myArray.length];
for(int i = 0;i<myArray.length;++i)
{
temp[i] = this.myArray[i];
}
return temp;
}
public ArrayList<Integer> getMyArrayList()
{
ArrayList<Integer> temp = new ArrayList<Integer>();
for(int i = 0;i<myArrayList.size();++i)
{
temp.add(this.myArrayList.get(i));
}
return temp;
}
public void setMyArray(int[] newArray)
{
if(newArray.length!=myArray.length)
{
return;
}
for(int i = 0;i<myArray.length;++i)
{
this.myArray[i] = newArray[i];
}
}
public void setMyArrayList(ArrayList<Integer> newArrayList)
{
for(int i = 0;i<myArrayList.size();++i)
{
this.myArrayList.add(newArrayList.get(i));
}
}
}
Is what I have illustrated with the above code the proper way to implement getter and setter methods for Arrays and ArrayLists respectively? I assume that it would be better to return copies of the Arrays and ArrayLists in the getter methods as well as set each individual element in the Array/ArrayLists in the setter methods. If this is incorrect, please illustrate the proper method for implementing these methods.