In your getMyPrivateArrayList ()
function, do the following:
public List<SomeDataStructure> getMyPrivateArrayList(){ return Collections.unmodifiableList(myPrivateArrayList); }
Collections.unmodifiableList(someList)
returns a read-only list.
<h / "> In your calling class, if you try to modify the returned list, you will get a runtime error, for example.
If you follow these
List<SomeDataStructure> readOnlyList=getMyPrivateArrayList(); readOnlyList.add(new SomeDataStructure());
You will get the following error:
Exception in thread "main" java.lang.UnsupportedOperationException at java.util.Collections$UnmodifiableList.add(Collections.java:1160) at MainClass.main(MainClass.java:14)
source share