I suggested returning Collections.unmodifiableList() instead of directly returning a member variable, and my colleague is concerned that there would be a performance hit. Of course the best answer is to measure it, and we may do that - but I'd like to know your experiences and any references, pro or con.
An unmodifiable collection is often a copy of a modifiable collection which guarantees that the collection itself cannot be altered. Attempts to modify it will result in an UnsupportedOperationException exception. It is important to notice that objects which are present inside the collection can still be altered.
Convenience static factory methods on the List, Set, and Map interfaces let you easily create unmodifiable lists, sets, and maps. A collection is considered unmodifiable if elements cannot be added, removed, or replaced.
No. At least, the OpenJDK implementation literally "replaces" the modification methods with UnsupportedOperationException
s, the rest adds one level of indirection, which should just get optimized away by the compiler VM (and even so, one level of indirection wouldn't be costly).
If you wish to return a list that cannot be modified, any performance impact would pale in comparison to the loss in correctness, I wouldn't avoid it for performance alone, and I certainly wouldn't avoid it if it's what you need.
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