Example code:
modifyMyList(myList); public void modifyMyList(List someList){ someList.add(someObject); }
or:
List myList = modifyMyList(myList); public List modifyMyList(List someList){ someList.add(someObject) return someList; }
There is also a 3rd option I believe: You can create a new List in modifyMyList method and return this new List...
( 3rd option is here, I was too lazy but someone already added it in the answers: )
List myList = modifyMyList(myList); public List modifyMyList(List someList){ List returnList = new ArrayList(); returnList.addAll(someList); returnList.add(someObject); return Collections.unmodifiableList(returnList); }
Is there any reason why I should choose one over another? What should be considered in such case?
It depends on what guarantees you want to provide the user. If the data is sequential such that the order of the elements matter and you are allowing duplicates, then use a list. If order of elements does not matter and duplicates may or may not be allowed, then use a collection.
The list() method of java. util. Collections class is used to return an array list containing the elements returned by the specified enumeration in the order they are returned by the enumeration.
The List interface in Java provides a way to store the ordered collection. It is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements.
I have a (self imposed) rule which is "Never mutate a method parameter in a public method". So, in a private method, it's ok to mutate a parameter (I even try to avoid this case too). But when calling a public method, the parameters should never be mutated and should be considered immutable.
I think that mutating method arguments is a bit hacky and can lead to bugs that are harder to see.
I have been known to make exceptions to this rule but I need a really good reason.
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