If I return Collection I can return unmodifiable version from Collections class. Is there something for arrays? I know I can build another array and copy it, but maybe there is solution without performance price?
I think an unmodifiable Collection is the way to go.
But if you do end up cloning the array, then be sure that you make a "deep copy." Otherwise, the copied array will contain references to the same element objects as the original. (Yet another reason to go with the unmodifiable Collection.)
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
But if you do end up cloning the array, then be sure that you make a "deep copy."
Which would mean we're not really cloning it, right? Cloning an array returns a shallow copy.
Otherwise, the copied array will contain references to the same element objects as the original. (Yet another reason to go with the unmodifiable Collection.)
Errr... no. That is, if we're talking about an array or collection of mutable objects, then Collections.unmodifiableCollection() is just as vulnerable to abuse as a cloned array is. Try this:
Using unmodifiableList() and similar methods only protects the collection itself from modification. If the objects inside the collection are mutable, then they are not protected. If you need to make absolutely sure the data in your original collection remains unmodified, you need a deep copy. Period.
Safe are only unmodifiable collections of immutable objects. It seems to me that this guarding is not practical. It will steal performance and also programmer time. So it must be done for secure systems, like banking software etc mostly. The best thing I came up with - trust people who use your code Unless of course you work with very sensitive data, as mentioned before.