I am wondering what's the time complexity of Collections.unmodifiableList?
If I want to make an incoming Collection immutable, what's the cheapest way?
I am wondering what's the time complexity of
Collections.unmodifiableList?
Collections.unmodifiableList returns a view of its argument list as opposed to a copy, so it's O(1). This is typically how you'd create an immutable list, but be sure to not change the original mutable list, since those changes will be reflected in the newly created immutable list. This shouldn't be a problem if you keep the original list private. This is the situation I'm talking about:
List<String> modifiableList = new ArrayList<>();
List<String> unmodifiableList = Collections.unmodifiableList(modifiableList);
System.out.println(unmodifiableList);
modifiableList.add("hello");
System.out.println(unmodifiableList);
[] [hello]
This happens because unmodifiableList is a view (and not a copy) of modifiableList.
Time complexity for which operations?
For all non-modifying operations, it would be in the same O notation as the underlying data structure.
For all modifying operations, it probably would be just a bit faster (early error exiting).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With