如何获得不可修改的 LinkedHashSet
How to get an unmodifiableLinkedHashSet
有Collections.unmodifiableCollection()
和Collections.unmodifiableSet()
但没有Collections.unmodifiableLinkedHashSet()
保留顺序的正确选择是什么?
Collections.unmodifiableSet(Set)
返回的 Set
只是您作为参数提供的 Set
的包装。
Returns an unmodifiable view of the specified set. This method allows
modules to provide users with "read-only" access to internal sets.
Query operations on the returned set "read through" to the specified
set, and attempts to modify the returned set, whether direct or via
its iterator, result in an UnsupportedOperationException
.
换句话说,所有 read 活动的行为方式与您直接访问目标 Set
的方式完全相同。所有 write 活动均失败。
所以只需将它与您的 LinkedHashSet
一起使用即可。
LinkedHashSet<?> someSet = ...
Set<?> wrapper = Collections.unmodifiableSet(someSet);
有Collections.unmodifiableCollection()
和Collections.unmodifiableSet()
但没有Collections.unmodifiableLinkedHashSet()
保留顺序的正确选择是什么?
Collections.unmodifiableSet(Set)
返回的 Set
只是您作为参数提供的 Set
的包装。
Returns an unmodifiable view of the specified set. This method allows modules to provide users with "read-only" access to internal sets. Query operations on the returned set "read through" to the specified set, and attempts to modify the returned set, whether direct or via its iterator, result in an
UnsupportedOperationException
.
换句话说,所有 read 活动的行为方式与您直接访问目标 Set
的方式完全相同。所有 write 活动均失败。
所以只需将它与您的 LinkedHashSet
一起使用即可。
LinkedHashSet<?> someSet = ...
Set<?> wrapper = Collections.unmodifiableSet(someSet);