0

Collections.unmodifiableSet allows me to create an unmodifiable view of a set. I'm assuming this is done by wrapping the provided set. Will there be any performance problem(s) if unmodifiable sets are created from already unmodifiable sets?

e.g.

Set<String> set = Collections.unmodifiableSet(Collections.unmodifiableSet(Collections.unmodifiableSet(new HashSet<String>())));
Linus
  • 3,254
  • 4
  • 22
  • 36

2 Answers2

0

Collections.unmodifiableSet - just wraps a set with UnmodifiableSet instance, which just proxies all method invocation. Additional finite method invocation sequence is not a subject of performance consideration, sure if you are not talking about thousands of wrappers.

Mikhail
  • 4,175
  • 15
  • 31
0

The method signature is:

public static <T> Set<T> unmodifiableSet(Set<? extends T> s) {
    return new UnmodifiableSet<T>(s);
}

in the class Collections. Which returns a new instance of object UnmodifiableSet. Now this class is inner static class:

static class UnmodifiableSet<E> extends UnmodifiableCollection<E> implements Set<E>, Serializable

In the class UnmodifiableCollection the methods like add, remove, addAll etc throws UnsupportedOperationException. That is why it is Unmodifiable.

Now if you instantiate thousands time a collection of course it would be issue.

Tapas Bose
  • 28,796
  • 74
  • 215
  • 331