Welcome to the CSC Q&A, where you can get help (and share your knowledge) about computer science!

returning an ArrayList in an instance method, or a copy of one

+14 votes
Is it advisable to use a private ArrayList in your class, and have an instance variable return it? private ArrayList listr; public ArrayList getListr() { return listr; } Why or why not? If not, what could you do to improve the instance method?
asked Oct 19, 2015 in Fall 15-16 by Nick Caputo (100 points)
edited Oct 26, 2015 by Nick Caputo
Might want to fix your askmethis tag just in case...
Maybe we should ask Metgis about all our problems. Especially weather-related ones.
Also, can you edit your question title to be more descriptive of the problem?

2 Answers

+9 votes
 
Best answer
I assume that since it is private, you don't want other classes to be able to change it. If you return the list in a get method, client code can call .add() or .remove() on it and change the list. If you don't want to be able to change it, the get method should return a copy.
answered Oct 21, 2015 by Michael J. Currie (100 points)
selected Oct 21, 2015 by Nick Caputo
+5 votes
I am not sure what you are looking for but if you don't intend to change the original arrayList or rather want to have a copy of the original arrayList wouldn't it be better to just clone the arrayList, that way you have reference to the original list, prototype pattern. But if you are planning on updating the  original arrayList, what is the point of making it private and then having bunch of setters and getters to update the lists failing to utilize the fact that arrayLists are mutable? The third scenario, which might be the scenario you were getting at - you only care for the data in the arrayList and dont intend to change its values. For instance, an arrayList that returns a list of completed orders to be displayed in the GUI Table, then if this is the case then I think the current design is just fine. Unless am missing something.
answered Oct 20, 2015 by Nelly Cheboi (100 points)
edited Oct 21, 2015 by Nelly Cheboi
...