An instance of Class A has a private ArrayList. The instance is responsible for maintaining data stored in the arrayList.
private ArrayList<SomeDataStructure> myPrivateArrayList;
However, when other module ask for the data, this instance of Class A will have to pass the data the whoever asks for it, therefore, there is public function in Class A:
public ArrayList<SomeDataStructure> getMyPrivateArrayList ();
My question, how should I implement this function so that I could guarantee that those who get the arrayList through this public function won’t be able to modify it (i.e., the return value is read-only)?
Thanks in advance!
I would suggest doing this instead (if you’re allowed to in your situation):
Note that the exposed data structure is of type
Listinstead ofArrayList. I think (generally speaking) the public interface of a class should not return concrete types, but rather should return interfaces. It simplifies tasks such as this one, and also reduces the amount of dependancy that one class has on the implementation of another class.