Why can we change the unmodifiable list if we have the original one?

前端 未结 7 764
时光取名叫无心
时光取名叫无心 2020-12-10 15:56

By looking at the code of Collections class, i got to know that when we are using the method unmodifiableList(List list) or unmodifiableCollection(Coll

7条回答
  •  甜味超标
    2020-12-10 16:12

    (answer of the queston at the bottom)

    When you create an unmodifiable list, the purpose is that it should not be modified by people other than you - i.e. clients of an API.

    the method unmodifiableList(..) creates a new object of type UnmodifiableList (but this is not a public class), which gets the original list, and delegates all methods to it except the methods which would modify it.

    The point is, as stated in the documentation:

    Returns an unmodifiable view of the specified list. This method allows modules to provide users with "read-only" access to internal lists.

    So, an example: You have a List of devices that your API has detected and can operate, and you want to give them a client of your API. But he is not supposed to change them. So you have two options:

    • give him a deep copy of your List, so that even if he modifies it, this does not change your list
    • give him an unmodifiable collection - he can't modify it, and you spare the creation of a new collection.

    And now here comes the answer to the title of your question - the unmodifiable list is a view of the original collection. So if you need to add a new item to it - say, you have discovered a new device that was just plugged-in, the clients will be able to see it in their unmodifiable view.

提交回复
热议问题