I need to return List member variable from my class. If I do return List contained in class then the caller will be able to modify it. I do not want anybody to be able to modify List. If I do return cloned List it's ok, but cloning is expensive. I saw people returning Iterator to list. That would be the best except for Iterator has remove() method. How to properly return a list that can be viewed but cannot be modified?
Why are you so sure of that? Did you do timing trials? Seems to me that a shallow clone should not take any more time than creating a wrapper object. The clone method in java.lang.Object involves native code - presumably a pure copy operation. Bill
Collections.unmodifiableList() is a good start, but not necessarily good enough. Imagine that you need to return a list of lists. Then unmodifiableList will only make the top-most list unmodifiable. Users will still be able to get references to the "internal" lists and change them.
Niether shallow copying helps you in this case. The only solution is that all members of the List are unmodifiable too.