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.
It depends on what you are trying to do, in some cases keeping it somewhat immutable is useful, which looks like what you are going for. You can write the methods a bit more concisely like so.
private int[] myArray = {1,2,3,4,5};
private ArrayList<Integer> myArrayList = new ArrayList<Integer>();
public int[] getMyArray()
{
return Arrays.copyOf(myArray, myArray.length);
}
public ArrayList<Integer> getMyArrayList()
{
return new ArrayList<>(myArrayList);
}
public void setMyArray(int[] newArray)
{
this.myArray = Arrays.copyOf(newArray, newArray.length);
}
public void setMyArrayList(ArrayList<Integer> newArrayList)
{
this.myArrayList = new ArrayList<>(newArrayList);
}
there is no harm in implementing getters and setters for arrays or ArrayLists if you deem it necessary.
For arrays, there is a copyOf and copyOfRange methods which you can use to copy an array into a new array rather than doing it yourself.
As for ArrayLists, there is a copy constructor which you can use to construct a new ArrayList containing the elements of the specified collection instead of doing it yourself as well an addAll method to append all of the elements in the specified collection to the end of another list.
as for:
I assume that it would be better to return copies of the Arrays and ArrayLists
again it depends if you deem it necessary to make the array or ArrayList immutable which depend upon certain factors of what you're trying to achieve.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With