I was looking the javadoc of List to find a method that allow replacement of a element ( set(int, E) ) and I saw that the method is "optional". I searched for a while and found this other question with a great answer from Laurence Gonsalves.
But I still have a question, until now everytime I used any interface, I never expected that a implementation could throw an runtime exception (unless I used it wrong or if it was a bug in the implementation code), even though I had exception when accidently tried to add elements to an immutable List, I didn't realized what was going on.
My question is: if I have an API method that has a List (or some other interface) parameter that has to invoke "optional" operations on that object how should I proceed?
- Should I avoid using List, and use some implementation as parameter?
- Should I make a defensive copy of the list, modify it and return that list? (this could change the implementation used by the api client)
I know that the need to change a list received as a parameter in a method is questionable, but it may be necessary