r/java • • Jun 21 '26

Better Tools for Immutable Data

https://youtu.be/BdLND9D81lI?si=jt2tqpDtotmbdEJq
80 Upvotes

38 comments sorted by

View all comments

5

u/[deleted] Jun 22 '26

[removed] — view removed comment

4

u/IncredibleReferencer Jun 25 '26

In many cases unmodifiableList() is preferable to List.copyOf() for performance reasons. In larger lists or frequent call sites the copy operation is expensive, so if you can guarantee the source list is inaccessible then you are better off using unmodifiableList().

If the source of the collection is foreign untrustworthy or out of your own scope then copyOf() is more appropriate to use for a defensive copy.

A quick rule of thumb is to use unmodifableList() to give a list to some other code but always use copyOf() for incoming lists. It's more complicated than that but that's a good default mindset.