What is the difference between google's ImmutableList and Collections.unmodifiableList ()?

后端 未结 5 1266
孤城傲影
孤城傲影 2020-12-08 02:11

From ImmutableList javadocs:

Unlike Collections.unmodifiableList(java.util.List), which is a view of a separate collection that can still change

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-08 02:45

    Using Collections.unmodifiableList creates a wrapper around your List. if the underlying list changes, so does your unmodifiableList's view.

    As the documentation says, Google's code creates a copy. It's a more expensive computation and consumes more memory, but if someone alters the original list, it cant affect the ImmutableList.

    Neither of these will prevent you from changing an object in a list, or it's fields, or fields of fields, etc.

提交回复
热议问题