Collections.unmodifiableSet允许我创建一个不可修改的集合视图。我假设这是通过包装提供的集合来完成的。如果从已经不可修改的集合中创建不可修改的集合,是否会有任何性能问题?
例如
Set<String> set = Collections.unmodifiableSet(Collections.unmodifiableSet(Collections.unmodifiableSet(new HashSet<String>())));
Collections.unmodifiableSet允许我创建一个不可修改的集合视图。我假设这是通过包装提供的集合来完成的。如果从已经不可修改的集合中创建不可修改的集合,是否会有任何性能问题?
例如
Set<String> set = Collections.unmodifiableSet(Collections.unmodifiableSet(Collections.unmodifiableSet(new HashSet<String>())));
Collections.unmodifiableSet - 只是用 UnmodifiableSet 实例包装一个集合,它只是代理所有方法调用。额外的有限方法调用序列不是性能考虑的主题,如果你不是在谈论成千上万的包装器。
方法签名是:
public static <T> Set<T> unmodifiableSet(Set<? extends T> s) {
return new UnmodifiableSet<T>(s);
}
在课堂Collections
上。它返回一个新的 object 实例UnmodifiableSet
。现在这个类是内部静态类:
static class UnmodifiableSet<E> extends UnmodifiableCollection<E> implements Set<E>, Serializable
在类中UnmodifiableCollection
,方法如add
,remove
等。这就是为什么。addAll
throws UnsupportedOperationException
Unmodifiable
现在,如果您实例化数千次集合当然会出现问题。