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

后端 未结 5 1252
孤城傲影
孤城傲影 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:43
    1. No, the contained individual objects can still be modified. A collection is really only storing references to the contained objects, not a full copy of every object.
    2. You can modify the list by modifying the parent Collection you called Collections.unmodifiableList(list) on. But yes, you CAN use setDimension to change a stored list element.
    0 讨论(0)
  • 2020-12-08 02:45

    No, the immutability is only applied to the amount and references of the objects in the Collection, and does not address the mutability of objects you put in the Collection.

    What Immutable list gains over the standard JDK Collections.unmodifiableList is that by using ImmutableList you are guaranteed that the objects referenced, their order and the size of the list cannot change from any source. With Collections.unmodifiableList if something else has a reference to the underlying list, that code can modify the list even though you have a reference to an unmodifiable list.

    If, however, you want true immutability, you have to fill the list with immutable objects.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-08 03:02

    ImmutableList is similar to Collections.unmodifiableList( new ArrayList( list ) ) . Note that the newly created ArrayList is not assigned to a field or variable.

    0 讨论(0)
  • 2020-12-08 03:05

    You might also want to take a look at this question (What's the difference between Collections.unmodifiableSet() and ImmutableSet of Guava).

    0 讨论(0)
提交回复
热议问题